如何仅使用JavaScript创建像Moustache {{}}这样的简单视图引擎 [英] How can I create simple view engine like Mustache {{ }} using JavaScript only

查看:80
本文介绍了如何仅使用JavaScript创建像Moustache {{}}这样的简单视图引擎的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建像Mustache这样的简单视图引擎,以便将{{}}之间的单词替换为它的值,例如:

How can I create simple view engine like Mustache, so that the word between the {{ }} is replaced by its value, like:

<p>hey there {{ codeName }}</p>
codeName = 'JavaScript 6'
so that it be converted to:

<p>hey there JavaScript 6</p>

推荐答案

我发现以下是理解它的正确方法:

I found the below to be proper way to understand it:

var templater = function(html){
  return function(data){
  for(var x in data){
    var re = "{{\\s?" + x + "\\s?}}";
    html = html.replace(new RegExp(re, "ig"), data[x]);
  }
  return html;
 };
};

var template = new templater("<p>hey there {{ codeName }}</p>");
var div = document.createElement("div");
div.innerHTML = template({
  codeName: "JavaScript 6"
 });
 document.body.appendChild(div);

引用是此处

这篇关于如何仅使用JavaScript创建像Moustache {{}}这样的简单视图引擎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆