Dan Barbarito
Dan Barbarito

Reputation: 480

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

Upvotes: 2

Views: 3586

Answers (1)

zeantsoi
zeantsoi

Reputation: 26193

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 (e.g., %(day)s) instead of positional interpolation (e.g., %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} }}

Upvotes: 2

Related Questions