You can’t create a custom function in Power Pages liquid, but you can get close enough

By | September 20, 2024

Have you ever thought of creating a custom function in liquid to reuse it in multiple places?

Technically you can’t, not a custom function. However, you can create web templates as components, and that allows us to use such templates almost in the same way we’d be using functions.

For example, you could easily re-use tag replacement liquid code if you defined a template like this:

You could use it in your liquid code to do tag replacement. And you can use “capture” liquid tag to assign results to variables:

Notice how, in the loop above, the template is included for each step, so it does text replacement, and, then, the output gets captured in the “result” variable.

Which is simply added to the HTML output in this case, but you can do whatever you want with it. Basically, we have a function, even if takes a bit of an effort to define it.

Here is the code if you wanted to try:

{% manifest %} 
    { 
    
    "type": "Functional", 
    "displayName": "ReplaceTag", 
    "description": "Replace Tag Example", 
    "params": [ 
        {
            "id": "text",
            "displayName": "Text",
            "description": "Text"
        },
        {
            "id": "tag",
            "displayName": "Tag Name",
            "description": "Tag Name"
        }
        ,
        {
            "id": "replacement",
            "displayName": "Replacement",
            "description": "Replacement"
        }
        ] 
    } 
{% endmanifest -%}
{% assign splitText = text | split: tag -%}
{% assign textReplacement = replacement | string -%}
{{splitText | join: textReplacement-}}

As for the loop, don’t forget all those hyphens when testing. Otherwise, you may think the template is adding “spaces” to the output, but it’s not, it’s just that all those tags in the loop, since they are on different lines, will be adding spaces to the right/left of them (and this is why there are hyphens all around)

Leave a Reply

Your email address will not be published. Required fields are marked *