Inclusion Tags in Django on Google App Engine
I want to create a reusable template (almost like a UserControl from the .NET world) that I can apply in multiple places, something like:
{% for thing in things %}
{% render_thing thing %}
{% endfor %}
Where render_thing is my custom inclusion tag. My Python code reads as follows:
def get_full_path(relative_path):
return os.path.join(os.path.dirname(__file__), relative_path)
def render_thing(thing):
return {'thing':thing }
register = template.create_template_register()
register.inclusion_tag(开发者_StackOverflowget_full_path('thing.html'))(render_thing)
Where thing.html is my little template. However, when I run this I get the error:
TemplateSyntaxError: Invalid block tag: 'render_thing'
What am I missing?
If you are using Django 1.2 templates, you will need to supply a Python module-style reference to your custom tag code rather than a file path.
There's a full description of the problem and the solution on my blog.
EDIT: Sorry to be so high-level on you. Here's a more step-by-step explanation:
Put your custom tag code in a file, say
my_custom_tags.py
for the sake of example.take the .py file that your custom tag code lives in and put it in a subdirectory of your main AppEngine project directory, say
customtags
for the sake of an example.- in that new subdirectory, create an empty file that has the name
__init__.py
in your AppEngine application's main
.py
file, add this code:from google.appengine.ext.webapp import template template.register_template_library('customtags.my_custom_tags')
All of the custom tags defined in your custom tag library should now be available in your template files with no additional work.
load template tag
{% load my_template_library %}
see manual
- http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
- http://www.mechanicalgirl.com/view/custom-template-tags-in-django/
- http://www.protocolostomy.com/2009/08/05/practial-django-projects-custom-template-tags-and-updates-on-linuxlaboratory/
You need to load the templatetag library within each template that uses it.
{% load my_template_library %}
精彩评论