Meteor Template Inside Script Tag

I want to fill a tag script type="text/html

with the Meteor template.

So this is a weird thing, I know. Half of the reason I want to do this is because Cloud9 cannot distinguish between JS script tags and HTML script tags, and its syntax highlighting and tag breaks end up when I try to write HTML in tags.Other script

half I'm just curious to see, maybe is it because there is an ugly looking workaround.

So this:

<body>
    <script type="text/html" id="test">
        {{> test}}
    </script>
</body>

<template name="test">
    <span>Test</span>
</template>

      

Produces the following:

<script type="text/html" id="test">
    <!--label:YRgyaMH8-->
</script>

      

Does anyone have a way to make it render the template instead of what looks like evaluating the name as a comment?

+3


source to share


2 answers


Posting another answer b / c I would like to keep my previous one for records only. I think this approach will work better.

Within your html, you will define two sections. First, you are going to host your template code. It will go into the comment inside a simple div tag. Second, where the template will be placed to use Knockout. It looks like this:

<template name="koTemplate">
    <div id="myTemplate">
        <span>Here is my template <a href="#">with children</a></span>
    </div>

    <script type="text/html" id="test"></script>
</template>

      

Then in your client JS code you will add a callback to run when the template is rendered



Template.koTemplate.rendered = function () {
  // Get the first node, then get the content inside of it
  var templateHtml = this.firstNode.innerHTML;

  // Remove the element so it doesn't get rendered
  this.firstNode.parentNode.removeChild(this.firstNode);
  // another option is to surround the contents inside the template w/comments, but that loses syntax highlighting

  // Get the target node for placing the template in
  var templateNode = this.lastNode;

  // place the content from the original node to the target node
  templateNode.innerHTML = templateHtml;
};

      

This will basically get the content of the template, remove the template, and then put it in script tags. The result will look like this:

<script type="text/html" id="test">
    <span>Here is my template <a href="#">with children</a></span>
</script>

      

+1


source


I would advise to abandon the use of the script tag and instead use some other generic tag that Cloud9 won't consider as JS and Meteor won't come up with. Using the example in my comment on the question, it would look something like this:

<div id="template">
  <!--<span>test</span>-->
</div>

      

And in your JS, you will parse this:



var template = document.getElementById('template').firstChild.nodeValue,
    result = parseTemplate(template, values);

      

This is the main idea. You will need to convert it to parsing the Knockout pattern after getting the result.

0


source







All Articles