2012-08-28 41 views
7
傳遞變量給宏

我做,我使用,以顯示其文本線和標籤的一些小宏:在Jinja2的

{% macro input(name, text, help_text, value="", input_type) -%} 
    <label for="id_{{name}}">{{text}}<span class="right">{{help_text}}</span></label> 
    <input id="id_{{name}}" name="{{name}}" value="{{value}}" type="{{input_type}}" /> 
{{%- endmacro %} 

問題是,當我打電話Jinja2的宏:

{{input("username", "Korisničko ime:", "Pomoć", {{value_username}}, "text")} 

當我使用{{value_username}}作爲參數調用輸入時,我無法使其正常工作,但我總是遇到錯誤。

您是否知道任何解決方案我如何才能撥打{{value_username}}作爲參數。

回答

11

我相信

{{ input("username", "Korisničko ime:", "Pomoć", value_username, "text") }} 

應該工作

+4

謝謝,即使使用過濾器,它也能很好地工作。 但是,如果有其他字符串追加或準備好變量(例如=>「你好{{value_username | capitalize}},早上好!」),是否可以將這種字符串傳遞給宏?我試圖避免使整個字符串成爲一個單一的變量,因爲有很多prepped和append組合。 –

2

雖然埃米特J.巴特勒提供了一個答案,有一個小雞蛋裏挑骨頭與宏觀參數的順序。您目前使用以下簽名:

input(name, text, help_text, value="", input_type) 

你應該始終把包含默認值規定的所有其他參數之後,因此更改訂單到這個參數:

input(name, text, help_text, input_type, value="") 

現在用變量調用宏時參數,因爲您已經在{% ... %}之內,所以您不需要用{{ }}來包圍變量。