django - 如何在 Django 中获取自定义模板标签的可选参数?

标签 django templates django-1.4

我刚刚创建了一个自定义模板标签。

from django import template
from lea.models import Picture, SizeCache
register = template.Library()

@register.simple_tag
def rpic(picture, width, height, crop=False):
    return SizeCache.objects.get_or_create(width=width, height=height, picture=picture, crop=crop)[0].image_field.url

除可选参数 crop 外,此方法有效。可以设置可选参数,但会被函数忽略并始终设置为 False。

最佳答案

simple_tag 与 Python 调用类似。

如果您在模板中传递文字 True,它将被视为名为 True 的变量并在模板上下文中进行搜索。如果没有定义True,值变成''并被Django强制为False,只要crop 字段是一个 models.BooleanField

例如,

在 foo/templatetags/foo.py 中

from django import template
register = template.Library()

def test(x, y=False, **kwargs):
    return unicode(locals())

在外壳中

>>> from django.template import Template, Context
>>> t = Template("{% load foo %}{% test 1 True z=42 %}")
>>> print t.render(Context())
{'y': '', 'x': 1, 'kwargs': {'z': 42}}

# you could define True in context
>>> print t.render(Context({'True':True}))
{'y': True, 'x': 1, 'kwargs': {'z': 42}}

# Also you could use other value such as 1 or 'True' which could be coerced to True
>>> t = Template("{% load foo %}{% test 1 1 z=42 %}")
>>> print t.render(Context())
{'y': 1, 'x': 1, 'kwargs': {'z': 42}}
>>> t = Template("{% load foo %}{% test 1 'True' z=42 %}")
>>> print t.render(Context())
{'y': 'True', 'x': 1, 'kwargs': {'z': 42}}

关于django - 如何在 Django 中获取自定义模板标签的可选参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10597423/

相关文章:

c++ - 如何为模板函数实现容器和迭代器的重载?

python - 将 ManyToMany 字段从一个模型实例复制到另一个模型实例

python - 尝试对用户执行索引搜索(django-haystack)

sql - 如果值为null则Postgresql忽略过滤条件

c++ - 将迭代器传递给函数

c++ - 如何为其他类成员函数编写模板包装器方法?

django - 当还给出实例时如何为 ModelForm 设置初始值

python - "ImportError: No module named jobs.models"相对路径

python - 如何从多进程(子进程)获取django.db.connection.queries数据?

python - 更新 Django-Select2 AutoModelSelect2Field 的查询集