【问题标题】:How to replace information in the file with tokens and without PHP?如何在没有 PHP 的情况下用令牌替换文件中的信息?
【发布时间】:2021-04-08 10:10:33
【问题描述】:

我创建了一个小网站,这是我的文件:

https://github.com/S1BIOSE/E-business-Card

我将这些文件放在使用 HTML、JS 和 CSS 的免费主机上。它不支持 PHP。

我想创建令牌来替换 JS、HTML、JSON、XML 和 TXT 文件中的信息。例如:

  • 带有公司名称的令牌。
  • 带有网站网址的令牌。
  • 带有公司描述的令牌。

【问题讨论】:

  • 你想从哪里加载这些令牌?您希望它们成为文件还是应该成为您网址的一部分?
  • @EmilS.Jørgensen 例如,我想在所有文件中更改公司名称“Mathieu LEBERT”。
  • 只需稍加努力,您就可以将存储库转换为使用 Jekyll 并在 Github 页面上免费托管该站点,并使用自定义域,并使用 _config.yml 来存储一些变量/令牌。

标签: javascript html token


【解决方案1】:

如果没有某种服务器端编程,您将无法即时更改文件。

在前端,您可以在 URL 中包含令牌或通过 AJAX 加载。

以下是在 URL 中使用查询字符串的示例:

function LoadAndApplyTokens() {
  const urlParams = new URLSearchParams(window.location.search);
  document.querySelectorAll('*').forEach(tag => {
    for (let i = 0; i < tag.childNodes.length; i++) {
      const child = tag.childNodes[i];
      if (child.nodeName.toLowerCase() != '#text') {
        continue;
      }
      let val = child.nodeValue;
      let change = false;
      let variables = val.match(/::[^:]+::/img);
      if (variables == null)
        continue;
      variables.forEach(variable => {
        if (urlParams.has(variable.substr(2, variable.length - 4))) {
          const variableValue = urlParams.get(variable.substr(2, variable.length - 4));
          while (val.indexOf(variable) >= 0) {
            val = val.replace(variable, variableValue);
          }
          change = true;
        }
      });
      if (change) {
        child.nodeValue = val;
        console.log(child.parentNode, val);
      }
    }
  });
}
window.addEventListener("load", LoadAndApplyTokens);
<div>
  <h1>My name is <b>::name::</b></h1>
  <p><b>Description of ::name::</b><br/>::name:: is a company</p>
</div>
<form method="get">
  <label>Name: <input name="name" /></label>
  <button type="submit">Change</button>
</form>

【讨论】:

  • 好的谢谢我明白了,所以只能编辑HTML?我将无法使用此解决方案修改 JS 或 CSS 文件的内容?
  • 那么你可以在你的 HTML 中有一个 style 元素,上面的函数可以操作。但正确的做法可能是某种服务器端功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
  • 2017-12-11
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多