stencilproject / Stencil

Stencil is a simple and powerful template language for Swift.
https://stencil.fuller.li
BSD 2-Clause "Simplified" License
2.34k stars 224 forks source link

Can I pass variables when I using include tag? #265

Closed diuming closed 5 years ago

diuming commented 5 years ago

Hi, As title, can I do that? please following. thanks

index.stencil

<html>
    {% include "head.stencil" myTitle={{ obj.title }} %}
    <body>
    .
    .
    .
    </body>
</html>

head.stencil

<head>
    <meta charset="utf-8">
    <title>Software: {{ myTitle }}</title>
</head>
AliSoftware commented 5 years ago

According to the documentation:

By default the included file gets passed the current context. You can pass a sub context by using an optional 2nd parameter as a lookup in the current context.

So yes you totally can.

In your example just pass obj as the second parameter in the tag, and in the included template you'll be able to use n{{ title }} to get that variable. (Alternatively don't pass any 2nd parameter to your include tag and access {{ obj.title }} directly from the included template)

ilyapuchka commented 5 years ago

the object passed to the include tag should be a dictionary, so what @AliSoftware said. Also it's not possible to use {{ }} inside other tags IIRC.

diuming commented 5 years ago

@AliSoftware and @ilyapuchka I got it. thanks