开发者

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:

  1. Put your custom tag code in a file, say my_custom_tags.py for the sake of example.

  2. 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.

  3. in that new subdirectory, create an empty file that has the name __init__.py
  4. 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 %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜