简体   繁体   中英

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

I want the events.html template to format the string somehow, but I do not know how I would do that. The way I have it below is how I would think it should work, but it doesn't.

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}); 

Why interpolate when you don't need to? Try the following:

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

Another thought: regarding your string interpolation, the docs say the following:

For this reason, you should use named-string interpolation (eg, %(day)s) instead of positional interpolation (eg, %s or %d) whenever you have more than a single parameter. If you used positional interpolation, translations wouldn't be able to reorder placeholder text.

So, first off, you need to enclose the arguments to be interpolated as a dict , which dictates that they're enclosed in curly brackets, not parentheses as you have in your code. Then, you should use named parameters, rather than relying on positional interpolation.

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

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