ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# `set` Inside code blocks you can also assign values to variables. Assignments usethe `set` tag and can have multiple targets. Here is how you can assign the `bar` value to the `foo` variable: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{% set foo = 'bar' %} </pre></div></td></tr></table> After the `set` call, the `foo` variable is available in the template likeany other ones: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2</pre></div></td><td class="code"><div class="highlight"><pre>{# displays bar #} {{ foo }} </pre></div></td></tr></table> The assigned value can be any valid [*Twig expressions*](#): <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3</pre></div></td><td class="code"><div class="highlight"><pre>{% set foo = [1, 2] %} {% set foo = {'foo': 'bar'} %} {% set foo = 'foo' ~ 'bar' %} </pre></div></td></tr></table> Several variables can be assigned in one block: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5 6</pre></div></td><td class="code"><div class="highlight"><pre>{% set foo, bar = 'foo', 'bar' %} {# is equivalent to #} {% set foo = 'foo' %} {% set bar = 'bar' %} </pre></div></td></tr></table> The `set` tag can also be used to 'capture' chunks of text: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5</pre></div></td><td class="code"><div class="highlight"><pre>{% set foo %} &lt;div id="pagination"&gt; ... &lt;/div&gt; {% endset %} </pre></div></td></tr></table> Caution If you enable automatic output escaping, Twig will only consider thecontent to be safe when capturing chunks of text. Note Note that loops are scoped in Twig; therefore a variable declared inside a`for` loop is not accessible outside the loop itself: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5</pre></div></td><td class="code"><div class="highlight"><pre>{% for item in list %} {% set foo = item %} {% endfor %} {# foo is NOT available #} </pre></div></td></tr></table> If you want to access the variable, just declare it before the loop: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5 6</pre></div></td><td class="code"><div class="highlight"><pre>{% set foo = "" %} {% for item in list %} {% set foo = item %} {% endfor %} {# foo is available #} </pre></div></td></tr></table>