我正在写一个小的django应用程序来处理图像。 我想让它尽可能干,所以这是我的目标:
用户上传一个文件,并输入一些字段,如标题、alt text、title等。。在
在模板上,我希望能够执行以下操作:
model.image.render_tag
会产生如下结果:
^{pr2}$问题是该行应该在模板上,这样如果开发人员需要添加一些内容或删除其他内容,他们可以编辑模板,并且所有渲染图像中的渲染都会发生变化。在
还可以添加第二个模板并呈现该模板。在
现在,有几种方法可以实现这一点:
只需包含一个呈现名称空间变量的模板,并强制开发人员每次“更改”图像变量名称,模板将类似于:
<img src="{{ namespaced_image.raw.path }}" alt_text="{{ namespaced_image.alt_text }}"... />
在这种情况下,开发人员应该在包含路径之前将图像重命名为其名称空间版本。在
比如:
{% with namespaced_image=image %}
{% include images/template.html %}
{% end with %}
根据用户可以在设置中编辑的原始字符串,添加一个模板标记来呈现图像,如下所示
设置.py
namespaced_image_tag="<img src={path} ... />"
我的模板标签会做一些类似的事情
@register
def rendered_tag(image)
return namespaced_image_tag.format(path=image.raw.path, ...)
因此开发人员只需添加自定义标记文件并使用
{% load images_filters %}
{{ image|rendered_tag }}
上述各项的混合物:
会出现违约模板.html包含标记,以及一个模板标记,通过将名称空间的图像作为上下文来呈现模板。在
@register
def rendered_tag(image, template="default_template.html")
return render_template(template, namespaced_image=image)
所以开发者可以做一些类似的事情
{% load images_filters %}
{{ image|rendered_tag }}
{{ image|rendered_tag:"custom_template_name" }}
但是,我不知道每个请求呈现多个模板会如何影响性能。在
另外,我不太喜欢选项1,因为它既不可用又不可读。在
选项2不好,因为我不能使用不同的“模板”,也不能扩展其他模板。我也不太喜欢模板标记,特别是因为用户被迫在每个使用过的模板中导入文件。在
在可用性方面,选项3是最好的,但是我觉得它会影响很多性能。有什么提示吗?在
在我看来,而且我认为很多人都同意我的观点,一个模型不应该对它在HTML中的表示负责,所以在我看来,
model.image.render_tag
是错误的。在应用程序中唯一知道如何用HTML表示任何内容的部分应该是视图及其模板。在
您可以有一个helper函数来为图像生成HTML,并在视图中使用它,还可以使用一个引用该函数的
simple_tag
,以便在模板中使用它。在如果在模板中调用它的性能有问题,请考虑使用一个性能更好的模板引擎-您可以参考这个SO answer获取模板引擎的基准测试,或者可以在视图中调用该助手函数,并通过上下文将结果传递给模板。在
更新
我将用一个例子来说明我上面的意思。在
^{pr2}$
^{3}$
上面的代码使用模板中的
image_to_html
助手函数,方法是使用我们创建的image_tag
simple_tag
。另一种可能的方法是在视图中调用image_to_html
,并将结果传递给模板:相关问题 更多 >
编程相关推荐