Set default value of inline substitution in Chameleon

105 views Asked by At

Is there a way to set a default value for an ${}-style inline field in a Chameleon template so when it parse it does not die?

>>> from chameleon import PageTemplate
>>> template = PageTemplate("<div>Hello ${name}.</div>")
>>> template()
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/chameleon/utils.py", line 404, in __getitem__
    return dict.__getitem__(self, key)
KeyError: 'name'

The documentation has some complex formats, but I cannot find this. But, given how obscure it is to figure that, say, ${structure: name} does not escape html leaving it alone, I might have missed it.

The best I have come up with is a decorator for my Pyramid view functions under the view_config decorator...

1

There are 1 answers

0
benvc On

For anyone looking for a default or fallback in your Chameleon template expressions, you can do something simple like:

${variable | 'default'}

However, be aware that setting a default or fallback in this way will bypass NameErrors for your template variables which could complicate debugging.