【问题标题】:Inclusion Tags in Django on Google App EngineGoogle App Engine 上 Django 中的包含标签
【发布时间】:2011-07-15 10:31:56
【问题描述】:

我想创建一个可以在多个地方应用的可重用模板(几乎就像 .NET 世界中的 UserControl),例如:

{% for thing in things %}
    {% render_thing thing %}
{% endfor %}

render_thing 是我的自定义包含标签。我的 Python 代码如下:

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)

thing.html 是我的小模板。但是,当我运行它时,我得到了错误:

TemplateSyntaxError: Invalid block tag: 'render_thing'

我错过了什么?

【问题讨论】:

  • 你使用的是什么版本的 Django?应用引擎上的当前默认值相当旧 - 0.96。
  • 对,我尝试添加 use_library('django','1.2') 代码,但它错误地说它无法识别 use_library :(
  • 糟糕,忘记导入了。有趣,已修复 - 现在有一个新错误 TemplateSyntaxError: Invalid block tag: 'render_activity', expected 'empty' or 'endfor'

标签: python django google-app-engine django-templates


【解决方案1】:

如果您使用的是 Django 1.2 模板,则需要为您的自定义标记代码提供 Python 模块样式的引用,而不是文件路径。

有一个full description of the problem and the solution on my blog

编辑: 很抱歉对你这么高水平。这是一个更一步一步的解释:

  1. 将您的自定义标记代码放在一个文件中,例如 my_custom_tags.py

  2. 获取自定义标记代码所在的 .py 文件,并将其放在 AppEngine 项目主目录的子目录中,例如 customtags

  3. 在那个新的子目录中,创建一个名为__init__.py 的空文件
  4. 在您的 AppEngine 应用程序的主 .py 文件中,添加以下代码:

    从 google.appengine.ext.webapp 导入模板 template.register_template_library('customtags.my_custom_tags')

您的自定义标签库中定义的所有自定义标签现在应该可以在您的模板文件中使用,无需额外工作。

【讨论】:

  • 嗨亚当,恐怕这并没有真正的帮助。它可能对 Python/GAE 忍者有所帮助,但我真的不知道我需要做什么才能开始。
  • @ConfusedNoob;我添加了更明确的步骤。希望对您有所帮助。
  • 我自己设法破解了它,但我认为您的回答会对我遇到的其他人非常有帮助,谢谢!
【解决方案2】:
【解决方案3】:

您需要在每个使用它的模板中加载模板标签库。

{% load my_template_library %}

【讨论】:

    猜你喜欢
    • 2010-12-07
    • 2010-11-03
    • 2011-01-11
    • 2012-05-23
    • 2010-10-20
    • 1970-01-01
    • 2011-04-23
    • 2012-08-15
    • 2010-11-28
    相关资源
    最近更新 更多