簡體   English   中英

HTML 模板到 Javascript 字符串文字

[英]HTML template to Javascript String Literals

感謝您的任何反饋...

我有一個嵌入了 JS 字符串文字的 HTML 模板......

<html>
  <head>
   <title>${title}</title>
  </head>
  <body>
   User name: ${user.name}
  </body>
</html>

那我在做...

let temp = require('./template.html')

return temp; // <--- I need this to return the compiled html

如何獲取要呈現的字符串文字?

甚至有可能做到這一點嗎?

我需要 'temp' 變量作為編譯字符串返回,以便稍后在代碼中將其插入到 document.write 中。

謝謝。

這些不是字符串文字。 它們看起來像 JavaScript 模板文字中的標記。

甚至有可能做到這一點嗎?

如果您的意思是要動態加載 HTML,然后將其用作模板文字,那么您只有兩種選擇:

  • 使用解析字符串並處理這些標記的模板庫(或編寫您自己的模板代碼)

  • 使用eval / new Function

eval (或new Function與您自己的內容一起使用時並不邪惡(並且性能成本被大大誇大了),盡管我並不是說我會推薦它。 但這就是你要做的(假設在你的堆棧中, require('./template.html')會給你一個包含內容的字符串):

let temp = require('./template.html');
const template = "`" + temp.replace(/`/g, "\\`") + "`";

(你可能想在那里做更多的轉義,我只是處理了反引號。)

然后,當您在范圍內擁有相關令牌時:

const str = eval(template);

現場示例:

 let temp = document.getElementById("template").textContent.trim(); const template = "`" + temp.replace(/`/g, "\\\\`") + "`"; // Using it const title = "This is the title"; const user = {name: "Joe Blogs"}; const str = eval(template); console.log(str);
 <script type="text/template" id="template"> <html> <head> <title>${title}</title> </head> <body> User name: ${user.name} </body> </html> </script>


為什么eval而不是上面的new Function 這樣包裝模板供使用的代碼就不必知道名稱titleuser new Function仍然允許任意代碼執行,就像eval一樣,所以你仍然不能使用它,除非你自己的內容......

您可以創建一個新函數將其轉換為字符串模板

return new Function("title","user","return `" + temp + "`;")(title,user);

正如 TJ 所指出的,您需要知道模板中使用的所有變量,並將它們作為函數的參數包含在內。

是的,可以對您的代碼進行一些小的修改。 首先將template.html重命名為template.js並將其內容更改為

exports default ({title, user}) =>`
    <html>
       <head>
        <title>${title}</title>
       </head>
       <body>
         User name: ${user.name}
       </body>
    </html>`

然后let temp = require('./template.js')將一個函數分配給 temp,您應該使用您的上下文調用它。 就像是

let ctx = { title: 'titre', user: { name: 'alice' } }
let compiled = temp(ctx) // your compiled template

查看yo-yo一個圍繞這個概念工作的庫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM