Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Supercharge views with shortcodes

Supercharge views with shortcodes

Talk about the Shortcode library.

Tomasz Kowalczyk

March 09, 2018
Tweet

More Decks by Tomasz Kowalczyk

Other Decks in Programming

Transcript

  1. $handlers = new HandlerContainer(); $handlers->add('b', function(ShortcodeInterface $s) { return '<strong>'.$s->getContent().'</strong>';

    }); $parser = new RegularParser(); $processor = new Processor($handlers, $parser); $text = 'My name is Bold. Text [b]Bold[/b].'; $result = $processor->process($text); // My name is Bold. Text <strong>Bold</strong>.
  2. $syntax = new Syntax('[[', ']]', '//', '==', '""'); $parser =

    new RegexParser($syntax); $processor = new Processor($handlers, $parser); $text = 'My name is Bold. Text [[b]]Bold[[//b]].'; $result = $processor->process($text);
  3. $eventHandler = function(FilterShortcodesEvent $event) { $p = $event->getParent(); if($p &&

    ($p->getName() === 'raw' || $p->hasAncestor('raw'))) { $event->setShortcodes([]); } }; $events = new EventContainer(); $events->addListener(Events::FILTER_SHORTCODES, $eventHandler); $processor = new Processor(new RegularParser(), new HandlerContainer()); $processor = $processor->withEventContainer($events); assert(' [name /] ' === $processor->process('[raw] [name /] [/raw]'));
  4. final class ShortcodeTwigExtension extends \Twig_Extension { public function getFilters() {

    return [new \Twig_SimpleFilter('shortcode', [$this, 'processShortcodes'])]; } public function processShortcodes($text) { $handlers = new HandlerContainer(); $handlers->add('b', new WrapHandler('<strong>', '</strong>')); $parser = new RegularParser(); $processor = new Processor($handlers, $parser); return $processor->process($text); } }