Skip to content

Common issues with snowman templates and scripting

jackdarker edited this page Feb 28, 2021 · 2 revisions

Access Scope

Template methods have only a limited scope: The code within a template method only has access to things in global scope and things defined within this template method. If you have a passage like this (assuming that you have in global scope setup window.gm.printMyFirstHeader):

:: Test
<%=window.gm.printMyFirstHeader()%>
<%=printMySecondHeader()%>
<script>
printMySecondHeader(){
return("<h2>Second header</h2>");
}
</script>

The first Template method will work (function assigned to global object), but the second not because the template method doesnt see the local script-section of the passage.

However, this is possible: :: Test2
<%="<a href='javascript:void(0)' onclick='onclick()'>Click this</a>"%>
<script>
onclick(){ alert("clicked");}
</script>

The template will return only a html-Text describing a link. But the method does not need to parse or execute onclick, because its just text. But after the method is executed, we now have a link on our page that is connected with the script from the page.

Conclusion: if you need to call functions from template method, they have to be in global scope.

Unexpected <

This is often related to some issue inside passage scripts. Try to use debugger to pinpoint which.

One unobvious reason can be that you added scripts to your passage and their are some complete empty lines inside. When the tweego compiler processes the passage, it seems to sometimes insert <p></p> here. Which of course will mess up the scripts.

Other ways to create dynamic pages

Run script on page load, get a parent DOM-node and add html elements by using innerHtml or outerHtml.

The example will insert the paraphrase into the div. :: Test3
<div id="panel"></div>
<script>
function buildShopPanel() {
$("div#panel")[0].innerHTML="<p>The shop is closed.</p>";
}
buildShopPanel();
</script>

Clone this wiki locally