Search code examples
javascriptdojosubstitution

How to parse/render a html string with Dojo 1.10?


Let's say I have the following :

const props = {
    buttonText : 'Click Me'
}

const htmlString = "<button>${buttonText}</button>"

dojo.someFunction(htmlString, props);

What would be the dojo module equivalent of "someFunction"?

I understand it can be done with templateMixins, but I don't want to extend/make a widget, only borrow the parsing function.


Solution

  • All you have to do is using the dojo/string -> substitude function that's used in the dojo Dijit’s templating.

    See below working snippet :

    require(["dojo/string", "dojo/dom","dojo/ready"], function(string, dom , ready) {
    
      const props = {
        buttonText: 'Click Me'
      }
    
      const htmlString = "<button>${buttonText}</button>"
      
      var newString = string.substitute(htmlString, props);
      console.log(newString);
      alert("String after substute : \n"+ newString);
      dom.byId("btn").innerHTML = newString ;
      
    });
    <script type="text/javascript">
      dojoConfig = {
        isDebug: true,
        async: true,
        parseOnLoad: true
      }
    </script>
    
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
    <link href="//ajax.googleapis.com/ajax/libs/dojo/1.8.3/dijit/themes/claro/claro.css" rel="stylesheet" />
    
    <div id="btn"></div>