繁体   English   中英

如何获取Django模板以使用字符串格式?

[英]How can I get a Django template to use string formatting?

我希望events.html模板以某种方式设置字符串格式,但是我不知道该怎么做。 我在下面看到它的方式是我认为它应该工作的方式,但事实并非如此。

events.html

{% extends "base.html" %}
{% block content %}
{% for object in objects %}
<h1>{{object.name}}</h1>
<p>When: {{ "It will take place in the year %s and the month %s" % (object.when.year, object.when.month) }}</p>
{% endfor %}
{% endblock %}

views.py

from django.template.response import TemplateResponse
import pdb
from events.models import Event

def home(request):
    objects = Event.objects.all()
    return TemplateResponse(request, 'events.html', {'objects': objects}); 

为什么在不需要时进行插值? 请尝试以下操作:

<p>When: It will take place in the year {{ object.when.year }} and the month {{ object.when.month }}</p>

另一个想法:关于您的字符串插值, 文档说如下:

因此,只要您有多个参数,就应该使用命名字符串插值(例如,%(day)s)而不是位置插值(例如,%s或%d)。 如果您使用位置插值,则翻译将无法对占位符文本进行重新排序。

因此,首先,您需要将要插值的参数作为dict括起来,这表明它们用大括号括起来,而不是代码中的括号。 然后,应该使用命名参数,而不是依赖位置插值。

{{ "It will take place in the year %(year) and the month %(month)." % {'year': objects.when.year, 'month': objects.when.month} }}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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