【问题标题】:shell: HTML templating外壳:HTML 模板
【发布时间】:2020-10-08 22:01:41
【问题描述】:

我有一个小项目,其中包含一个 HTML 模板文件;

<p>Hi, I'm some text for this project!</p>

我希望它被我的 bash 脚本读取,但 Sed 在结束标记处转义,这不是最佳的;

目前看起来像这样($postContents 是上面的 HTML 文本);

## Replace <!-- TITLE --> in Head > Title and in Headder > H1 with RealName
sed -i "s/{{TITLE}}/$realname/g" $webdir/blog/$basefile
## Replace <!-- DATE --> With webdate
sed -i "s/{{DATE}}/$webdate/g" $webdir/blog/$basefile
## Replace <!-- CONTENTS --> With postContents
sed -i "s/{{CONTENTS}}/"$postContents"/g" $webdir/blog/$basefile

经过手动检查,我绝对确定它在结束标记上。我需要做些什么才能使其正常工作?

【问题讨论】:

  • Don't Parse XML/HTML With Regex. 我建议使用 XML/HTML 解析器 (xmlstarlet, xmllint ...)。
  • 向我们展示示例输入和预期输出,我们会给你很好的指示
  • 是模板文件吗?如果是,应该使用哪个工具来编辑它?
  • 好的,抱歉,是的。我应该提到这一点,但是在这个问题上猛烈抨击(对不起)我的头几个小时有点让我有点短。把手中的文字是模板文件中的目标,该模板文件从模板文件夹 ($webdir/template/postTemp) 复制到博客文件夹 ($webdir/template/slug),并在日期、可读名称等所有这些有趣的东西。
  • 我不知道是否有人删除了它,但我通过将 / dilimiator 与管道交换来让它工作。

标签: html bash sed


【解决方案1】:

最好使用真正的模板引擎。

我想到 perl Template::Toolkit 模块或 python Jinja。

使用tpage 实用程序,与perl 模块Template::Toolkit(Debian 上的包libtemplate-perl)一起安装:

cat template.tpl
<!DOCTYPE html>
<html lang="fr">
<head>
</style>
<title>[% title %]</title>
</head>
<body>
<a href="[% href %]" title="[% htitle %]" ></a>
<br/>
</body>
</html>

代码

$ tpage --define title=bar --define href=https://x.j/qs --define htitle=bar template.tpl 

输出

<!DOCTYPE html>
<html lang="fr">
<head>
</style>
<title>bar</title>
</head>
<body>
<a href="https://x.j/qs" title="bar" ></a>
<br/>
</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 2018-10-26
    • 2012-04-07
    • 2015-01-07
    • 2015-05-23
    • 1970-01-01
    相关资源
    最近更新 更多