Supercharge views with shortcodes

Supercharge views with shortcodes

Talk about the Shortcode library.

Bb29f6afb2ea244a12c25e04d46af19c?s=128

Tomasz Kowalczyk

March 09, 2018
Tweet

Transcript

  1. 2.
  2. 14.
  3. 16.

    $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>.
  4. 18.
  5. 19.
  6. 20.
  7. 24.

    $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);
  8. 27.

    $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]'));
  9. 33.

    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); } }