1

I have a client side CMS div that gets loaded into script template. I need to run a script inside that div. How can I run myFunction inside this script tag? It's closing the first script tag early :(

 <script type="text/html" id="tmpl-foo">

 <div id="myCMSdiv">

 <p> My Content </p>

 <script>
 myFunction();
 </script>

 </div>

 </script>
user3390251
  • 317
  • 2
  • 5
  • 22
  • I don't understand the question – Chris Dec 13 '16 at 18:44
  • This is invalid HTML, you can neither render the
    nor the
    – david Dec 13 '16 at 18:50
  • How did you place that JavaScript snippet in the html script in the first place? – AndrewL64 Dec 13 '16 at 19:15
  • updated. I have to add my content client side via a CMS. My content gets added to the page in the #myCMSdiv. I can put anything I want inside that div via the CMS but I can't control how it is placed on the page. (via the script template) – user3390251 Dec 13 '16 at 19:35
  • I believe that there is something wrong in your CMS - it should not place the
    inside the
    – david Dec 13 '16 at 20:26

1 Answers1

0

Give a bit of context of how your CMS binds the template (the JS file)
If your CMS uses template binding then you can just use afterRender.

Just like this:

var viewModel = function() {
  this.myFunction = function() {
    console.log("test");
  }
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div data-bind="template: { name: 'tmpl-foo', afterRender: myFunction }"></div>

<script type="text/html" id="tmpl-foo">

  <div id="myCMSdiv">
    <p>My Content</p>
  </div>

</script>

More info on template binding here.

If your CMS uses it as a component though then you need another approach.
Check this post on how to do it but the gist is just the same as above.

Community
  • 1
  • 1
Adrian
  • 1,597
  • 12
  • 16