Django の template 内で文字列の結合をしたかった。
文字列結合で生成した文字を変数に設定、その変数を別のタグに渡したい。
調べた結果、add
フィルターと、with
を使うと実現ができそうで、実際に実現ができた。
基本的に、Build-in フィルタの add
を使えば文字列の結合は実施可能
Built-in template tags and filters | Django documentation | Django
{{ 'testA'|add:"B" }}
文字列の場合は、連結、数値の場合は足し算になる。
add フィルターで、文字列を連結、連結した結果を attrs_str
として変数に受ける。
render_bundle
タグの変数として、attrs_str
を設定する。
以下、動作する実装。
{% with 'async defer chatset="UTF-8" crossorigin="anonymous" integrity="'|add:settings.BUNDLE_JS_SRI|add:'"' as attrs_str %}
{% render_bundle 'bundle' 'js' attrs=attrs_str %}
{% endwith %}
以下は、動作しない。
{% with 'async defer chatset="UTF-8" crossorigin="anonymous" integrity="'|add:settings.BUNDLE_JS_SRI |add:'"' as attrs_str %}
{% render_bundle 'bundle' 'js' attrs=attrs_str %}
{% endwith %}
settings.BUNDLE_JS_SRI
の後ろにスペースがあるのがまずいようで、以下のようなエラーになった。
django.template.exceptions.TemplateSyntaxError: 'with' expected at least one variable assignment
with 句では { with variable=222 }
記載もできる。
ただ、filterを使用するケースでの記載例が見つからなかったため、as で 変数名を記載した。
以下、参考にした記事。