I would like to set default values ββfor the variables used in my Jinja template inside the template itself. Looking at the Jinja2 documentation, I see no way to do this. Did I miss something? I see the "default" filter, but I want to set the template to a value of width instead of using it individually.
I spent an hour or so trying to talk enough about the process of writing Jinja2 extensions to write the setdefault
extension tag, which might look like this:
{% setdefault animal = 'wumpas' %}
The desired effect would be equivalent to the set
tag if the assigned name was undefined, but had no effect if the assigned name was defined. I, therefore, could not get this to work.
My job is to completely bypass the genie and create a complex file; the area before the special marker is (yaml) a display of default values, and the area after the marker is the jinja template. Proof of the implementation of this concept, which seems to work fine, is:
skel_text = """\ animal: wumpas %% The car carried my {{animal}} to the vet. """ class Error(Exception): pass _skel_rx = re.compile( r"""((?P<defaults>.*?)^%%[ \t]*\n)?(?P<template>.*)""", re.MULTILINE|re.DOTALL) _env = jinja2.Environment(trim_blocks=True) def render(skel, **context): m = _skel_rx.match(skel_text) if not m: raise Error('skel split failed') defaults = yaml.load(m.group('defaults') or '{}') template = _env.from_string(m.group('template') or '') template.globals.update(defaults) return template.render(**context) print render(skel_text) print render(skel_text, animal='cat')
So, is there a way to make the equivalent in stock Jinja2 or how can I write an extension to achieve the desired effect?
python jinja2
Matt anderson
source share