Jordan Lev Jordan Lev - 1 month ago 10x
Twig Question

Can an object tell Twig not to escape output when it is {{ printed }}

I've got a situation where some variables sent to my Twig templates are plain old variables, so I want them to be html-escaped (as is the default behaviour). But other variables sent to my templates are really objects with __toString() renderers... and some of these objects send out raw HTML (e.g. from a WYSIWYG editor like TinyMCE or CKEditor).

Ideally I'd like for my template designers to not have to use the

filter on the objects, but instead somehow have the objects tell Twig that they're already escaped.

In other words, I'm trying to mimc the behavior of a Twig function that sets
, but without requiring template designers to use a function.

E.g. I could write a Twig function using the
parameter in its definition and be able to have this in my templates:

{{ figure_out_what_to_do(something) }}

(where the
knows to inspect the "something" object to ascertain whether or not it needs to be escaped). BUT to me this is no better than having to remember to put
after every output of "something". So instead I'd like to be able to do this:

{{ something }}

...and have Twig recognize that
is an object and hence ask it whether or not it needs to be escaped.

I'm guessing the answer is "no", but figured I'd ask in case someone who knows more about Twig internals has any pointers for me.



In the __toString() method you could instead of return the html output, do this : return new Twig_Markup($html, 'UTF-8'); thus marking is as a safe and not to be escaped