twigsanitizationhtml-sanitizingtwig-filter

Is there some way to make Twig stop sanitizing HTML URL links?


Twig does a great job of sanitizing dangerous user input. However, I'm building a particular web app where I want to allow users to post clickable URL links in public comments. Is there some way I can make Twig not sanitize URL links, but still sanitize everything else?


Solution

  • You can use the raw filter to prevent HTML from being escaped:

    {{ some_html|raw }}
    

    Or maybe a better option would be to use it with the striptags filter and whitelist <a> tags:

    {{ some_html|striptags('<a>')|raw }}
    

    Internally, Twig uses the PHP strip_tags function. Note that its documentation has this warning:

    Warning

    This function does not modify any attributes on the tags that you allow using allowable_tags, including the style and onmouseover attributes that a mischievous user may abuse when posting text that will be shown to other users.

    See TwigFiddle.