简体   繁体   中英

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(get_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 my_template_library %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM