3
\$\begingroup\$

I've been trying to figure out how to stop Twig escape using the following code, which I feel is a little nicer with the succinct ternary operator.

I hope someone can confirm I'm using the correct syntax and if there are any performance issues doing it like this (as well as alternative methods, if any):

<body{{ bodyClass is defined ? (' class="' ~ bodyClass ~ '"')|raw : '' }}>

It seems to work and is the only way I've managed to get proper output so far!

An alternative version can be seen here, using string interpolation (#{} is my current preferred method):

" class=\"#{bodyClass}\""|raw
\$\endgroup\$
2
  • 4
    \$\begingroup\$ "Hoping someone can confirm I'm using the correct syntax" that makes it sound like you don't know if the code works. Did you mean to ask if it was in the correct style? \$\endgroup\$ Commented Dec 14, 2015 at 0:32
  • 1
    \$\begingroup\$ Ah, ok understood. I know |raw is the correct function to use, but I've never tried wrapping in parenthesis before (well, not with string interpolation anyway). So yes, I guess correct style would be more appropriate, thanks. Apparently it's good to go, but only for non-user editable templates. Twig has some interesting functions and seems like there are a vast many ways to use them! \$\endgroup\$
    – Rob
    Commented Dec 14, 2015 at 0:49

1 Answer 1

1
\$\begingroup\$

Does this work:

<body {{ bodyClass ? class='{bodyClass}'|raw : ''}}>

I don't think you need the brackets and tilde signs...

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.