Correct way to determine default variable values ​​from jinja template?

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?

+8
python jinja2
source share
2 answers

establish a management structure can do what you want.

Here is the code I used for testing:

 from jinja2 import Template t = '''{% set name=name or "John Doe" %}Hello {{ name }}''' template = Template(t) print template.render(name='Jonnie Doe') print template.render() 

As expected, it outputs:

 Hello Jonnie Doe Hello John Doe 
+11
source share

What worked for me was to use a filter:

 t = '''Hello {{name | default('John Doe')}}''' 
+21
source share

Source: https://habr.com/ru/post/650275/


All Articles