title: create templates on the fly / dynamically
body: <p>I am currently writing a django app around a rather complex data model.
  For many use cases, I need to build similar, but slightly differing templates (incl. graphviz etc..).</p>
  <p>Now I wonder if there is a way to follow DRY and create the templates &quot;on the fly&quot;, e.g. based on a nested tuple (of which one gets defined per use-case -&gt; template).</p>
  <p>Practically speaking I'd like to stop writing these:</p>
  <p><strong>static_template_case1.html</strong></p>
  <pre><code>{% if program %}
      {{ program.name }}
      {% for process in program.process_set.all %}
          {{ process.name }}
          {% for step in process.step_set.all %}
              {{ step.name }}
          {% endfor %}
          {% for control in process.control_set.all %}
              {{ control.name }}
          {% endfor %}
      {% endfor %}
  {% endif %}
  </code></pre>
  <p>and replace it with something in the following direction:</p>
  <p><strong>template_generator.py</strong></p>
  <pre><code>structure_case1 = (&quot;program&quot;(&quot;process&quot;(&quot;step&quot;,&quot;control&quot;)))
  
  def onTheFlyTemplate(structure):
      # iterate through structure
      # build template dynamically
      # return template
  
  onTheFlyTemplate(structure_case1)
  </code></pre>
  <p>I was not able to find something similar and also don't know yet where to start generating templates on the fly, nor how to integrate it.</p>
  <p>Within the views feels like a good starting point, (instead of <code>loader.get_template('static_template_case1.html')</code>).</p>
  <p>Thanks for any hint sending me into the right direction as well as your thoughts if DRY is being &quot;overdone&quot; here.</p>
  <p>Ralph</p>
  <h1>Edit</h1>
  <p>I got a step closer, doing the following:</p>
  <p>In the view:</p>
  <pre><code>from django.template import Template
  def templateGen():
      return Template(&quot;Program: {{program.count}}&quot;) 
  
  @login_required
  def test(request):
      program = Program.objects.all()
      t = templateGen()
      c = RequestContext(request,locals())
      return HttpResponse(t.render(c))
  </code></pre>
  <p>So far this is only a proof of concept. The real work will be to write a smart &quot;templateGen()&quot; listening to the nested tuple.</p>