loading...

Learn about javascript templates

dirkncl profile image Dirk Levinus Nicolaas ・3 min read

Modern JavaScript has provided templating, meaning javascript programming does not currently need to use library handelbars or mustcache, because modern Javascript has provided it with a combination of `` and ${}, I cannot explain this but is still curious.

This templates model really doesn't need to be made a library but can be used directly.
Let's experiment with the templates created by the library compared to direct use.

 <script>     
//templatingjs.js
var Template = function Template (template, Obj, Func) {
        return Template.transform (template, Obj, Func)
      }

      Template.convert = function convert (template, Functions) {
        return ExecTemplateFunc (template, Functions)
      }

      Template.transform = function transform (template, Obj, Functions) {
        if (typeof Obj === 'function') {
          Functions = Obj
          Obj = false
        }
        if (typeof Functions === 'function') {
          Template.convert (template, function (err, func) {
            if (err) return Functions (err)
            try {
                func (Obj)
            }
            catch (err) {
              Functions (err)
              return
            }
            Functions (null, func (Obj));

          })
          return
        }
        return ExecTemplateFunc (template) (Obj)
      }

      var ExecTemplate = function ExecTemplate (template) {
        if (typeof template! == 'string') {
          throw new TypeError ('ExecTemplate: expect `template` to be a string')
        }

        return function obj2func (Objs) {
          if (! (Objs! = null && typeof Objs === 'object' && Array.isArray (Objs) === false)) {
            throw new TypeError ('ExecTemplate: expect `Objs' to be an object')
          }

          var keys = []
          var vals = []

          for (var key in Objs) {
            keys.push (key)
            vals.push (Objs [key])
          }
          return new Function (keys, 'return `' + template + '`') .apply (Objs, vals)
        }
      }

      var ExecTemplateFunc = function ExecTemplateFunc (template, Func) {
        if (typeof Func === 'function') {
          try {
              ExecTemplate (template)
          }
          catch (err) {
            Func (err)
            return
          }
          Func (null, ExecTemplate (template));

          return
        }
        return ExecTemplate (template)
      }
    </script>     
  <div id='test'></div>
    <script>
      //function
      var UCaseFirstWord = function UCaseFirstWord(val) {
        var tmp = val.split(" ");
        var res="";
        for(i=0;i<tmp.length;i++)
          res += tmp[i].charAt(0).toUpperCase() + tmp[i].slice(1);
        return res
      };
      var rand = function rand(x){return (Math.random()*x)};
      var randLU = function randLU(low, up){ return Math.random() * (up - low) + low}
      //object
      var A = {
        num : 25,
        learn: {
          about: 'javascript programming,'
        },
        stupid: 'the more I did not understand.',
        ucfw: UCaseFirstWord,
        me:'Dirk Nicolaas',
        rand: rand,
        randLU: randLU
      }
      //template
      var sentenceFunc = '1. I learned ${ucfw(learn.about)} but the more I wanted to know, ${stupid} <br> ${me} <br> ${rand(num).toFixed(4)}<br>  ${randLU(20,80)}';

      //
      var sentenc1 = Template(sentenceFunc, A)
      console.log(sentenc1)
      document.write(sentenc1+'<br>')

      Template(sentenceFunc, A, function (err, sentenc2) {
        if (err) return console.error(err)
        console.log(sentenc2)
        document.write(sentenc2+'<br>')
      })
      /////////////////////////////
      //
      var ThreeJS = `https://threejs.org/build/three.js`;
      var sty = `display:inline`;
      var id = `experimen`;

      sentence = `2. I learned ${A.ucfw(A.learn.about)} but the more I wanted to know, ${A.stupid} <br> ${A.me}<br> ${A.rand(A.num).toFixed(4)}<br>  ${A.randLU(20,80)}`

      //HTML 
      var y = `
        <section>
          <div id=${id} style=${sty}>${sentence}<br></div>
        </section>
      `;
       document.getElementById("test").innerHTML = y;

        //Javascript loader
       document.write(`
         <script src=${ThreeJS}><\/script>
       `);

    </script>

*Due to the syntax of a template conflict conflict with yaml, the above program uses ~~~ yaml

At first glance this article is not useful at all for professional developers, but it is very useful to add insight to those who are still learning.

Conclusion

  • Learning javascript programming should be pure javascript, avoid using libraries or frameworks.

  • Using the Library or Framework is like we are still in middle school or high school, meaning that we accept what the textbook offers, without needing to know where a proposition or formula is obtained in a text book, what is important is to use it.

  • For programs that are not too large, you should immediately use the builtin syntax, no need to make small functions and be collected in one library.

Posted on by:

Discussion

markdown guide
 

Yes, you are right template literals is awesome addition to JavaScript but it's not replacement of JS frameworks.

And yes, you can do everything that JS framework can do with VanillaJS. But when you will need features that JS frameworks provide, then you will build that in VanillaJS which will be something like reinventing something that is invented (and maybe not sure with bugs 😞).

And one more thing template literals are not supported in old browsers.
Check it at: caniuse.com/#feat=template-literals