2014-01-05 48 views
0

我希望events.html模板以某種方式格式化字符串,但我不知道我會怎麼做。我在下面的方式是我會認爲它應該工作,但事實並非如此。我怎樣才能得到一個Django模板使用字符串格式?

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

它會拋出一個錯誤嗎?如果不是,輸出是什麼? 'object.when.year'和'object.where.month'都是整數嗎? – zeantsoi

+0

「無法解析餘數」我假設它將「%」作爲模運算符 –

回答

0

爲什麼當你不需要插值?請嘗試以下操作:

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

另一種思考:關於你的串插,the docs說以下內容:

出於這個原因,你應該使用命名字符串插補(例如,%(天)S)而不是位置插值(例如,%s或%d),只要您有多個參數。如果您使用位置插值,翻譯將無法重新排列佔位符文本。

所以,首先,你需要附上要插值爲字典,這決定了他們波形括號括起來,因爲你在你的代碼沒有括號內的參數。然後,您應該使用命名參數,而不是依靠位置插值。

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

嗯,我想這個例子並不是我真正需要的,但我認爲知道如何解決這個問題會很有用。但我真的沒有想到這樣做的基本方式,我想我累了.. –

+0

公平的。除了我最初的建議之外,我還提供了一個關於原始代碼中出現錯誤的解釋。如果有幫助,請考慮[接受這個答案是正確的](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – zeantsoi

相關問題