3

So, I'm in the process of building a fieldtype, and I'd like to output an HTML element and some javascript when a developer calls my plugin like this:

{{ entry.fieldtypeHandle }}

The field returns an object with other methods/properties on it, but I'd like to specifically provide something different when a developer calls my fieldtype without any other chaining.

I've tried pass a class with a __toString() method, but it just returns a string. (I don't know what I expected, honestly.) I also know that coupling the HTML output with the class seems a bit dirty, even if that did work.

Is this possible?

3

entry.myFieldHandle will return whatever the field type’s prepValue() function returns.

If you always want that to be HTML, then prepValue() can just return the HTML as a string or \Twig_Markup object via TemplateHelper::getRaw() so devs don't have to type |raw when outputting the value.

If you want it to be an object that supports sub-properties and methods, then have prepValue() return the object. Give the class a __toString() method, which defines the string that should be returned when the object is treated like a string. Behind the scenes, __toString() is what will be called when a template has {{ entry.myFieldHandle }}. But note that this is a PHP construct and PHP mandates that the method returns an actual string, so you can’t return a \Twig_Markup object here. Devs will have to type {{ entry.myFieldHandle|raw }} to prevent Twig from escaping the HTML.

1
  • Yeah, I was hoping that Craft did some magic with the result of the toString method, but it looks like I'll just have to put what I wanted to do into a method on the object that's returned. Thanks for the clarification! – Taylor Daughtry Aug 14 '16 at 19:18

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.