title: Sane way to define default variable values from within a jinja template?
body: <p>I'd like to set default values for variables used in my Jinja template inside of the template itself.  Looking at the Jinja2 documentation, I don't see any way to do this. Have I missed something? I see the "default" filter, but I want to set the value template wide instead of a use-by-use basis.</p>
  
  <p>I spent an hour or so trying to teach myself enough about the Jinja2 extension writing process to write an extension tag <code>setdefault</code>, which could look like this:</p>
  
  <pre><code>{% setdefault animal = 'wumpas' %}
  </code></pre>
  
  <p>The desired effect would be equivalent to the <code>set</code> tag if the assigned-to name was undefined, but to have no effect if the assigned-to name was defined. I have thusfar failed to get this to work.</p>
  
  <p>My work around is to circumvent jinja entirely and make a compound file; the area before a special marker is a (yaml) mapping of default values, and the area after a marker is the jinja template.  An proof of concept implementation of this that seems to work fine is:</p>
  
  <pre><code>skel_text = """\
  animal: wumpas
  %%
  The car carried my {{animal}} to the vet.
  """
  class Error(Exception): pass
  _skel_rx = re.compile(
      r"""((?P&lt;defaults&gt;.*?)^%%[ \t]*\n)?(?P&lt;template&gt;.*)""",
      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')
  </code></pre>
  
  <p>So, is there a way to do the equivalent in stock Jinja2, or how might one write an extension to accomplish the desired effect?</p>