DIV CSS 佈局教程網

17 行代碼實現 JavaScript 字符串模板引擎
編輯:關於JavaScript     

這個需求源自我做人生第一個真正意義上的網站時遇到的問題。項目採用前後端分離,後端 REST 接口返回 JSON,前端負責渲染。和很多初學者一樣,我最初用字符串拼接把數據塞進 HTML。代碼量少時還能忍,頁面結構一複雜,短板立刻暴露:

  1. 書寫不連貫:每寫一個變量就要斷一下,插入 + 和引號,極易出錯。
  2. 無法重用:HTML 片段是離散的字符串,重複部分難以抽取。
  3. 用不好 <template> 標籤:HTML5 推薦把模板放進 template 中,讓結構更清晰,拼接方式天然與之無緣。

需求描述

實現一個 render(template, context) 方法,用 context 填充 template 中的占位符。要求:

  • 不需要控制流(循環、條件等),只做變量替換。
  • 支持級聯變量展開。
  • 被轉義的分隔符 { 和 } 不應被渲染,分隔符與變量之間允許有空白字符。
render('My name is {name}', { name: 'hsfzxjy' });
// My name is hsfzxjy

render('I am in {profile.location}', { name: 'hsfzxjy', profile: { location: 'Guangzhou' } });
// I am in Guangzhou

render('{ greeting }. \\{ This block will not be rendered }', { greeting: 'Hi' });
// Hi. { This block will not be rendered }

第一步:匹配占位符

匹配交給正則表達式。根據需求一、二,先寫出最直觀的版本:

var reg = /\{([^\{\}]+)\}/g;

至於需求三,我最初想到前向匹配,可惜 JS 不支持,於是採用折衷方案——用分組捕獲轉義反斜線:

var reg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
// 若第一或第三個分組不為空,則說明被轉義,不渲染
function render(template, context) {
  var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
  return template.replace(tokenReg, function (word, slash1, token, slash2) {
    if (slash1 || slash2) {
      return word.replace('\\', '');   // 分隔符被轉義,去掉反斜線後原樣輸出
    }
    // ... 替換邏輯
  });
}

第二步:替換占位符

模板引擎不仅要能渲染一級變量,還要能渲染多級變量。做法很簡單:把 token 按 . 切開,逐級查找。

var variables = token.replace(/\s/g, '').split('.');   // 去掉空白並切割
var currentObject = context;
var i, length, variable;
for (i = 0, length = variables.length; i < length; ++i) {
  currentObject = currentObject[variable];
}
return currentObject;

但如果 token 指向的變量不存在,上面的代碼會報錯。為了更好的容錯體驗,可以在查找過程中判斷並提前返回空字符串:

var variables = token.replace(/\s/g, '').split('.');
var currentObject = context;
var i, length, variable;
for (i = 0, length = variables.length; i < length; ++i) {
  currentObject = currentObject[variable];
  if (currentObject === undefined || currentObject === null) return '';
}
return currentObject;

最終版本

function render(template, context) {
  var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
  return template.replace(tokenReg, function (word, slash1, token, slash2) {
    if (slash1 || slash2) {
      return word.replace('\\', '');
    }
    var variables = token.replace(/\s/g, '').split('.');
    var currentObject = context;
    var i, length, variable;
    for (i = 0, length = variables.length; i < length; ++i) {
      currentObject = currentObject[variable];
      if (currentObject === undefined || currentObject === null) return '';
    }
    return currentObject;
  });
}

除去空白行,一共 17 行。

掛到 String 原型上

通過修改原型鏈,還能實現更順手的調用方式:

String.prototype.render = function (context) {
  return render(this, context);
};

之後就可以這樣寫:

"{greeting}! My name is { author.name }.".render({ greeting: "Hi", author: { name: "hsfzxjy" } });
// Hi! My name is hsfzxjy.

當然,擴展原生原型存在污染風險,在多人協作或依賴較多的項目中,更建議把 render 作為獨立工具函數引入。而在支持 ES6 的環境裡,直接用模板字符串 `${ author.name }` 往往就能覆蓋大部分場景。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved