How can I specify what happens when someone calls my fieldtype without any further dot chains? 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?
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.