質問

Here is what my HTML code looks like:

<div class="post-content">
    <p>
       {{post.content}}
    </p>
</div>

I there any filter I can use to linkify any hash-tagged word in the post content using TWIG? Or I have to use JavaScript to that job?

役に立ちましたか?

解決

You can use the same Regular Expression-based method that this jQuery linkify plugin uses, just implemented in PHP instead of JavaScript.

You may need to tweak this a bit, but it should look something like this (boilerplate for TWIG plugin based on http://symfony.com/doc/current/cookbook/templating/twig_extension.html):

class LinkifyExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            'linkify' => new \Twig_Filter_Method($this, 'linkifyFilter', array('pre_escape' => 'html', 'is_safe' => array('html'))),
        );
    }

    public function linkifyFilter($text)
    {
        $pattern = "/\B#(\w+)/";
        $replacement = "<a href=\"HASHTAG_BASE_URL/$1\">#$1</a>";
        return preg_replace($pattern, $replacement, $text);
    }

    public function getName()
    {
        return 'linkify_extension';
    }
}

After you have registered your extension, you can use it like this:

{{post.content | linkify}}

他のヒント

You can use a twig extension with a method that'll linkify your hash-tagged word

first create an extension:

class PostExtension extends \Twig_Extension {

    protected $loader;
    protected $controller;

    public function __construct(FilesystemLoader $loader)
    {
        $this->loader = $loader;
    }

    public function setController($controller)
    {
        $this->controller = $controller;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return array(
            'hashTag' => new \Twig_Function_Method($this, 'hashtag', array('is_safe' => array('html'))),);
    }

    public function($word) {
        return // linkify word here
    }
}

Second :

add your extension as a service

  <service id="twig.extension.blogExtension" class="link\to\BlogExtension" public="false">
        <tag name="twig.extension" />
        <argument type="service" id="twig.loader" />
    </service>

and finally :

use it as a filter :

{{ word|hasgtag() }}

use can use a full text, according to what you'll implement in your method.

enjoy !!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top