• +43 660 1453541
  • contact@germaniumhq.com

Creating Python Handlebars Helpers


Creating Python Handlebars Helpers

If you’re using handlebars in python, you’re probably using pybars3. In handlebars most commands are defined by the language, such as {{if}} or {{each}}. What you need to know is that you can also write your own helper functions to extend the language. Here’s how to implement a switch clause:

What we want is to be able to parse code such as:

{{#each cool.items}}
{{#switch this.type}}
{{#case '1'}}MATCH: {{this}}{{/case}}
{{#default}}NO MATCH{{/default}}
{{/switch}}
{{/each}}

The good news is that pybars3 offers the possibility of creating such helpers. To achieve that we need to simply declare them as functions. They receive the parameters and the nested blocks to render:

from typing import Any, List

class SwitchEntry(object):
    """
    A Switch entry that is executing in the handlebars
    template.
    """
    switch_value: Any
    matched: bool

    def __init__(self,
                 switch_value: Any,
                 matched: bool = False) -> None:
        self.switch_value = switch_value
        self.matched = matched

switch_values: List[SwitchEntry] = []

def switch_call(scope, partials, value: object) -> Any:
    switch_values.append(SwitchEntry(switch_value=value))
    result = partials['fn'](scope)
    switch_values.pop()

    return result

def case_call(scope, partials, value: object) -> Any:
    if switch_values[-1].switch_value == value:
        switch_values[-1].matched = True
        return partials['fn'](scope)

def default_call(scope, partials) -> Any:
    if not switch_values[-1].matched:
        return partials['fn'](scope)

Register them in a map:

helpers = {
    "switch": switch_call,
    "case": case_call,
    "default": default_call
}

Then to use them in our template we need to:

hbs = pybars.Compiler().compile(source=template)
print(hbs(data, helpers=helpers))

If you want to use the switch/case/default, they are already defined as pybars3_extensions and published on pypi.

Simply import the helpers from the pybars3_extensions package.

Happy templating.