6

I've created a field type that stores its value as a model. That model’s __toString() method returns the result of a craft()->templates->render() call:

public function render() 
{
    $render = craft()->templates->render('myplugin/templates/mymodeltemplate');
    return $render;
}

public function __toString()
{
    return $this->render();
}

When I output the model from a template, like so:

{{ entry.myField }}

Twig encodes the resulting HTML as a string with HTML entities. Running the string through html_entity_decode() before returning it in __toString() doesn't help. I'm assuming this string formatting is happening somewhere at the Twig level.

Being new to Craft, I'd love to understand a little more of what's going on here. How does the string representation of an element model get passed to and handled by Twig?

  • Hey Angela, I’ve edited your question to focus on the first issue it was bringing up. Try to stick to that single-question format going forward. So your routing question should be its own separate question, for example. – Brandon Kelly Oct 9 '14 at 15:55
  • Thanks so much for helping me organize & navigate this, Brandon! – Angela T Oct 9 '14 at 18:08
4

Whenever you output anything with Twig’s {{ output tags }}, the contents will get encoded by default. You have to pass the content through the |raw filter in order for it to be output verbatim.

{{ entry.myFieldHandle|raw }}
  • 1
    Thanks, @Brandon Kelly. Passing the content through |raw works, but I'd like this work to be handled by my pugin on the backend. When I try returning TemplateHelper::getRaw($html) in my __toString() function, I get an Internal Server Error: __toString() must return a string. – Angela T Oct 10 '14 at 17:30
  • Doh! Guess you’ll have to stick with |raw :-/ – Brandon Kelly Oct 10 '14 at 18:05
2

Try this:

public function getFunctions() {
    return array (
        'my_func' => new \Twig_SimpleFunction('my_func', array($this, 'my_func'), array('is_safe' => array('html')))
    );
}

This being the important part:

array('is_safe' => array('html'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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