如何在 pugjs 的脚本中使用 HTML const 变量

问题描述

-
    const welcomeModalData = [ 
    { 
        title: "Stay on top of your health with timely reminders",description: "Lorem ipsum dolor sit amet." 
    },{ 
        title: "Stay on top of your health with timely reminders",description: "Get a personalized cost estimate..." 
    } 
    ]

p#title #{welcomeModalData[0].title} 
p#description #{welcomeModalData[0].description}
    
script. 
    document.getElementById("title").textContent = ${welcomeModalData[1].title}; // not working
    document.getElementById("description").textContent = ${welcomeModalData[1].description}; //not working

我将使用 pugjs 在脚本中将文本更改为 JSON 数据值。但我不知道如何在脚本中使用 JSON 数据。这些方法我都试过到现在都解决不了。

${welcomeModalData}
#{welcomeModalData}
JSON.parse(welcomeModalData)
json.stringfy(welcomeModalData)
...

任何人,你能帮我吗?

解决方法

您在 script 标签中使用了 plain text。从链接页面:

纯文本仍然使用标记和字符串 interpolation

所以这应该有效(它在我的机器上有效):

script.
  document.getElementById("title").textContent = "#{welcomeModalData[1].title}";
  document.getElementById("description").textContent = "#{welcomeModalData[1].description}";

未缩小的结果是:

<script>
document.getElementById("title").textContent = "Stay on top of your health with timely reminders";
document.getElementById("description").textContent = "Get a personalized cost estimate...";
</script>

即使用 #{myVariable}。记住引号。单引号也可以。

如果变量可能是多行文本,您可以使用 template literals,因为它们支持多行文本:

-
  const myVariable = `
    Look ma,I'm a multiline string!
  `

script.
  document.getElementById("title").textContent = `#{myVariable}`;

未缩小的结果:

<script>
document.getElementById("title").textContent = `
  Look ma,I'm a multiline string!
`;
</script>

关于您的评论:

如果我使用索引? 例如:var index = 1; featureTitle.textContent = "#{welcomeModalData[index].title}"; 但这是错误的

如果你的意思是这样的,那是不可能的:

script.
  const index = 1;
  document.getElementById("title").textContent = "#{welcomeModalData[index].title}";
  document.getElementById("description").textContent = "#{welcomeModalData[index].description}";

它不起作用,因为第一行 (const index = 1;) 只是纯文本,就像 script 标记的其余内容一样(不包括插值)。你不能混合 Pug 变量和打印的 JS 变量。

但是,您可以将 index 设为“Pug 变量”并在插值中使用它:

-
  const welcomeModalData = [
    // ...
  ]
  const index = 1;

script.
  document.getElementById("title").textContent = "#{welcomeModalData[index].title}";
  document.getElementById("description").textContent = "#{welcomeModalData[index].description}";

我不知道你在做什么,但这一切都让人感觉很脆弱。