for-loop in script-tag not working
markusBurda opened this issue · comments
I tried out this syntax:
$ const colors = ["red", "green", "blue"];
<ul>
<for|color| of=colors>
<li style={
color: color
}>${color}</li>
</for>
</ul>
<script>
<for|color| of=colors>
<p>loop-item</p>
</for>
</script>
Output:
<ul>
<li style="color:red;">red</li>
<li style="color:green;">green</li>
<li style="color:blue;">blue</li>
</ul>
<script>
<for|color| of=colors>
<p>loop-item</p>
</for>
</script>
Unfortunately marko does not compile my for-loop inside the script tag. How can I solve this?
Why do you want paragraphs inside <script>
? HTML itself won’t let you do that, and will instead parse the angle brackets as raw text:
<script>
<p>loop-item</p>
<p>loop-item</p>
<p>loop-item</p>
</script>
…is the same thing as:
<script><![CDATA[
<p>loop-item</p>
<p>loop-item</p>
<p>loop-item</p>
]]></script>
@markusBurda the <script>
tag has it's body parsed as text (<style>
and <textarea>
are the same) as @tigt mentioned.
If you want to dynamically generate a script you can still interpolate in text, eg:
<script>
window.x = ${JSON.stringify(input.something)};
</script>
Which is essentially the same as
<script>${`
window.x = ${JSON.stringify(input.something)};
`}</script>
The paragraph inside the script tag is just an example. I want to loop over an Array of ad-slots and initialize them by using something like this:
googletag.defineSlot('dfpUrl', [[970, 250], [800, 250]], 'div-gpt-ad-tile-11').setTargeting('tile', [11]).addService(googletag.pubads());
To prevent to make some stupid concat logic in my backend I wanted to make the loop in the template.
Very bad, that its not working as I expected, but I found this solution for me:
$ {
const els = ["a", "b", "c"];
let blub = "gtm.blub();";
els.forEach(function(item){blub += "console.log("+item+")"});
}
<script>
${blub}
</script>