Skip to content

Instantly share code, notes, and snippets.

@kemsakurai
Created June 24, 2018 14:35
Show Gist options
  • Save kemsakurai/5a1669a9fd5ffb64c21b4db5f341952b to your computer and use it in GitHub Desktop.
Save kemsakurai/5a1669a9fd5ffb64c21b4db5f341952b to your computer and use it in GitHub Desktop.
Djagno template 内で文字列を結合する

Django の template 内で文字列の結合をしたかった。
文字列結合で生成した文字を変数に設定、その変数を別のタグに渡したい。
調べた結果、add フィルターと、with を使うと実現ができそうで、実際に実現ができた。


add フィルター

基本的に、Build-in フィルタの add を使えば文字列の結合は実施可能
Built-in template tags and filters | Django documentation | Django

{{ 'testA'|add:"B" }}

文字列の場合は、連結、数値の場合は足し算になる。


with と add フィルターを使う

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 で 変数名を記載した。


参考

以下、参考にした記事。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment