Does appendTo for variables work across multiple levels of partials?

I see in a page I can use “appendTo: scripts” to add scripts to the parent _layout scripts. But if my page (say index.html) has a partial, and that partial also uses “appendTo: scripts” the script doesn’t get appended. Is there any way to accomplish what I want to accomplish? And while I’m on the subject of asking, if there is a way to do what I’m asking, is there a way to enforce a “just once…” scenario? Append the script to the parent, but only once! If the partial is used 4 times, only add the script once. One way I could see pulling this off is to set a variable on first add of the script and subsequent calls would be bypassed because the variable is already set. If this is possible, I’m not sure how to pull it off in the Web App framework.

It’s one of the reasons I loved the Spark View Engine over Razor. It’s multi-pass functionality allowed for nested views to enhance the calling view, like doing the above.

Partials get their own scope which behaves like re-declaring a variable in a local scope which shadows the outer scope variable and after the partial is evaluated the page only sees its own scoped variable.

But I’ve just added equivalent assignGlobal, appendToGlobal, prependToGlobal, addToGlobal, etc filters in this commit which instead of updating the variable in its local scope it updates the argument stored in the PageResult which is the context the page is rendered with that everything has accessed to, e.g. Layouts, Page, Partials, Filters, etc.

So if you use appendToGlobal all pages and partials will be updating the same variable.

This change is available from v5.1.1 which is now available on MyGet. Since you already have v5.1.1 installed you’ll need to clear your NuGet cache to fetch the latest version.

1 Like

FYI in the latest v5.1.1 the recommendation is to use the new {{#raw }} block as it ignores the body and emits it verbatim which will let you avoid any conflicts with any JavaScript containing {{...}}, e.g:

{{#raw appendTo scripts }}

Which saves to the same global variable as appendToGlobal.