Skip to content

Instantly share code, notes, and snippets.

@imathis
Last active December 17, 2015 19:58
Show Gist options
  • Save imathis/5663753 to your computer and use it in GitHub Desktop.
Save imathis/5663753 to your computer and use it in GitHub Desktop.
A proposal for how assign and capture could be extended to support appending to variables instead of simply assigning and thus overwriting them.

Append with capture/assign

I want to allow people to append to a varaible with capture or assign. Here is a syntax proposal. It was trivial to implement and it works with all new capture and assign modifications (post condition, ternary, etc).

Syntax

The main problem is which operator should I use. += or >>.

{% assign  foo = 'yo' %}                         // "yo"
{% assign  foo += ' man' %}                      // "yo man"
{% capture foo += %} what's up{% endcapture %}   // "yo man what's up"
{% assign  foo = nil %}                          // nil

or

{% assign  foo = 'yo' %}                         // "yo"
{% assign  foo << ' man' %}                      // "yo man"
{% capture foo << %} what's up{% endcapture %}   // "yo man what's up"
{% assign  foo = nil %}                          // nil

I like << better, but += might be more familiar to people. A downside of << is that it throws off syntax highlighters a bit.

highlighter demo

I should note that if a variable isn't defined, this will fall back to a simple assignment so there's no need for users to worry about that.

Example usage

I'm releasing a plugin for some kind of follow button. I've created a partial in my includes which contains the button code, but I want to inject the script at the bottom of the page. Here's what it could look like.

<a href="https://alpha.app.net/imathis/" rel='me'>follow @imathis</a>
{% capture post_scripts += %}
<script type="text/javascript">
...
</script>
{% endcapture %}

Then themes can support post script injection like this.

</footer>
</div>
{{ post_scripts }}
</body>

When a user includes the partial the script injection should just work.

{% include plugins/adn/follow.html %}

Of course users could also make use of this feature when installing scripts manually.

@parkr
Copy link

parkr commented May 28, 2013

I like this a lot!

One concern: how will scope be dealt with? Are all variables global?

@MrJoy
Copy link

MrJoy commented May 28, 2013

I'd say scope should be explicit in naming, using auto-vivification. I.E. foo.bar.baz for namespacing, with foo and foo.bar coming into existence on-demand as-needed.

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