我做在Django幾個徽章類,每個都包含某種描述在一個字符串變量:Django的定位有不願透露姓名的字符串參數
"You get this badge because you've runned %d meters in %d minutes"
"You get this badge because you've killed %d monsters of the type %s"
等等之類還有一個功能get_description(badge_level_requirements)
,所以在模板將與列表一起叫組裝字符串爲特定用戶:
class RunnerBadge(Badge):
des=ugettext_lazy("You get this badge because you've runned %d meters in %d minutes")
def get_description(cls,badge_level_requirements):
return cls.des%badge_level_requirements
而且我已經存儲在數據庫中的需求列表不帶任何參數的名稱已:(如示例所示,不同的班級有所不同t個數值來填充字符串,這些值也意味着不同的東西。所以我不能真正說出這些論點。
但是,如果我想將這些字符串國際化,將會出現錯誤:'msgid' format string with unnamed arguments cannot be properly localized
而且無法爲此問題生成語言文件。
有沒有辦法繞過這個錯誤?
更新
我碰到過這種方法繞過錯誤,而不更改數據庫。 在數據庫中,水平要求都存儲在文本字段在字典的格式:
#Requirment of Runner's badge
"{'gold':(100,10),'silver':(50,5),'bronze':(25,2)}"
,並在類的定義,添加碼的手動參數名稱爲「ARG_0」,「ARG_1」 ......以描述。在用於填充描述字符串之前,get_description方法被更改爲預處理數據。
class RunnersBadge(Badge):
requirements=#get the previous dict from database
description="You get this badge because you've runned %(arg_0)d meters in %(arg_1)d minutes"
@classmethod
def get_description(cls,level):
'''
This is actually a method of parent class Badge
level is either 'gold','silver' or 'bronze'
'''
dic={}
try:
for (num,val) in enumerate(cls.requirements[level]):
dic['arg_'+str(num)]=val
except TypeError:
dic['arg_0']=cls.requirements[level]
return cls.description%dic
該方法保留大部分當前結構(邏輯和數據庫)。翻譯者只需要照顧「放置」這個詞。
'runned'不是一個字。你應該用'ran'替換它。 – 2012-03-27 10:27:00
哈哈,這就是爲什麼我試圖繞過限制的一個跡象:) – 2012-03-27 13:00:40