Plugin template functions

Plugin template functions are defined with globalTemplateFunction(), and then are available in templates in all plugins. This allows you to write a plugin to provide functions to other plugins, but it does mean that you need to be careful to name them so they don’t clash.

If in doubt, prefix the function name with the name of your plugin, eg example_plugin:one.

When they are rendered, your JavaScript function is called with this set to a TemplateFunctionThis object, and passed arguments from the template.

Any return value from the function is output, appropriately escaped, in the template. Use the this object when you need to output HTML or render blocks.


Define a template function:

P.globalTemplateFunction("example:hello", function(name) {
  if(this.hasBlock(null)) {
  } else {
    this.write("Hello ");

Then use it in your template:

<div class="default">
<div class="block">
  example:hello("someone") { "Goodbye " }

Which, with an appropriate view, might output:

<div class="default">Hello John</div>
<div class="block">Goodbye someone</div>

If you only need to output some text which should be escaped according to the current context, it’s easier to just return a string:

P.globalTemplateFunction("example:hello", function(name) {
  return "Hello "+name;