2012-10-10 94 views
3

我將一個動態內容(從數據庫)拉到模板中。您可以將其視爲一些簡單的CMS系統。內容字符串包含一個模板變量。像這樣的(簡單情況):django模板 - 解析字符串變量裏面的變量

vars['current_city'] = "London" 
vars['content'] = 'the current city is: {{current_city}}' #this string comes from db 
return render_template(request, 'about_me.html',vars) 

然後在模板:

{{content}} 

輸出明顯:
當前城市是:{{current_city}}
預期:
當前城市是:倫敦

我的問題 - 是否有任何方法來呈現另一個變量內的變量名?使用自定義模板標記/過濾器似乎是一個好主意,但我試圖創建一個沒有成功......任何想法如何可以解決?

回答

4

有一個自定義的標籤也許可以解決這個問題,但是因爲當時有一個模板,因爲沒有限制您保存所有以dB爲單位的模板中有一個完整的模板的可能性,這可能會有點複雜(這可能包括其他模板標籤)。我認爲最簡單的解決方案是從數據庫中手動呈現模板字符串,然後將其作爲變量傳遞給主模板。

from django.template import Template, Context 
... 
context = { 
    'current_city': 'London' 
} 
db_template = Template('the current city is: {{current_city}}') # get from db 
context['content'] = db_template.render(Context(context)) 
return render_template(request, 'about_me.html', context) 

注:

如果你沿着這條路,這可能不是非常有效的,因爲每一次你將執行視圖,數據庫模板將不得不進行編譯。所以你可能想要緩存編譯好的數據庫版本,然後將適當的上下文傳遞給它。以下是非常簡單的緩存:

simple_cache = {} 

def fooview(request): 
    context = { 
     'current_city': 'London' 
    } 
    db_template_string = 'the current city is: {{current_city}}' 
    if simple_cache.has_key(db_template_string): 
     db_template = simple_cache.get(db_template_string) 
    else: 
     simple_cache[db_template_string] = Template(db_template_string) 
    context['content'] = db_template.render(Context(context)) 
    return render_template(request, 'about_me.html', context) 
+0

感謝您的支持。是的,鑑於我們擁有所有可用的變量,這並不是什麼大問題。如果解析不能在視圖內完成會怎樣? 這將是理想的,如果我們能有這樣的內容自動爲當前頁面拉出,一個視野之外,所以我們不必記住它,在模板上下文處理器爲例。然後我們最終得到一個字符串中的變量名,但是在這種情況下如何訪問模板變量來渲染字符串? – robertzp