javascript - Django include html without parsing template tags -
i'm creating django based web app server-side rendered. there few pages re-render using javascript feed.
i prefer use dry approach , re-use existing django templates, include them onto page inside tags.
then can use template library of choice (there many support django templates)
- jinjajs https://github.com/ericclemmons/jinja.js
- jinjajs ii https://github.com/sstur/jinja-js
- swig http://paularmstrong.github.io/swig/
- plate https://github.com/chrisdickinson/plate
- twigjs https://github.com/justjohn/twig.js
however i'm stuck on simplest thing, include template without parsing! here attempted approaches don't work
expected output
<ul> <li>john doe</a></li> <li>sally taylor</a></li> <li>david smith</a></li> </ul> <script type="text/template"> <ul> {% person in people %} <li>{{ person.name }}</a></li> {% endfor %} </ul> </script>
approach 1 - works have repeat same html twice
index.html
{% include "includes/list.html" %} <script type="text/template"> {% include "includes/list.html" script=1 %} </script>
list.html
{% if script = 1 %} {% verbatim %} <ul> {% person in people %} <li>{{ person.name }}</a></li> {% endfor %} </ul> {% endverbatim %} {% else %} <ul> {% person in people %} <li>{{ person.name }}</a></li> {% endfor %} </ul> {% endif %}
approach 2 - doesn't output after reaches loop
index.html
{% include "includes/list.html" %} <script type="text/template"> {% include_raw "includes/list.html" %} </script>
tags.py
from django import template django.template import loader, context register = template.library() @register.simple_tag def include_raw(templatename): return loader.get_template(templatename).render(context())
any appreciated!
so solved using solution: https://gist.github.com/henrikjoreteg/742160
the code make work was:
index.html
{% load pages_tags %} {% include "includes/list.html" %} <script type="text/template"> {% raw_include "includes/list.html" %} </script>
list.html
<ul> {% person in people %} <li>{{ person.name }}</a></li> {% endfor %} </ul>
pages_tags.py
from django import template, conf register = template.library() @register.simple_tag def raw_include(path): import os.path template_dir in conf.settings.template_dirs: filepath = '%s/%s' % (template_dir, path) if os.path.isfile(filepath): break fp = open(filepath, 'r') output = fp.read() fp.close() return output
here example project showing working together, including rendering client-side templates javascript:
https://github.com/kmturley/django-client-templates
and made jsperf test performance of different jinja style templating libraries:
Comments
Post a Comment