【问题标题】:Is there a tool for expanding XML document templates with XPath?是否有使用 XPath 扩展 XML 文档模板的工具?
【发布时间】:2018-08-29 05:37:06
【问题描述】:

我喜欢编写 HTML,并且倾向于使用很少的 JavaScript 编写平面网站。我一直在思考编写一种使用 XPath 和 XMLNS 来引用其他文档的新“语言”的想法。

我一直在尝试如何编写我的 HTML,然后我会运行一个构建工具来扩展和构建完整的文档。

有没有这样的工具?我宁愿重用或学习已经存在的工具。我怀疑我错过了一个明显或常见的工具,它已经做了类似的事情。

示例

这通常是我希望编写 HTML 的方式(或 HTMPL,因为它是模板,所以我一直这么称呼它)。

index.htmpl

<html xmlns:custom="card.htmpl">
    <custom:card img="/path/to/image.jpg">
        <title>Title content here</title>
        This is the card
    </custom:card>
</html>

card.htmpl

<div class="card">
    <img src="[[//card@img]]" />
    <div class="title">The title is: [[//card/title/text()]]</div>
    <div class="content">[[//card/text()]]</div>
</div>

结果

去掉多余的空格

<html>
    <div>
        <img src="/path/to/image.jpg" />
        <div class="title">The title is: Title content here</div>
        <div class="content">This is the card</div>
    </div>
</html>

【问题讨论】:

  • 立即让我想起 XSLT...

标签: html xml xpath templating


【解决方案1】:

XSLT 就是为完成这项工作而设计的。

XSLT 有一个名为“简化样式表”的概念,专为您需要非常简单的模板但很少使用简化样式表的情况而设计,因为大多数人发现他们最终需要完整的语言。

您的示例可以用 XSLT 3.0 编写(使用简化的样式表),如下所示:

data.xml

<custom:card img="/path/to/image.jpg">
    <title>Title content here</title>
    This is the card
</custom:card>

template.xsl

<html xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xsl:version="3.0" expand-text="yes">
  <div class="card">
    <img src="{//card/@img}" />
    <div class="title">The title is: {//card/title/text()}</div>
    <div class="content">{//card/text()}</div>
  </div>
</html>

但正如我所说,这种使用 XSLT 的方式并没有被证明很流行。

还有其他(非标准化)模板语言可用,例如 Velocity 和 Freemarker。在https://en.wikipedia.org/wiki/Comparison_of_web_template_engines 中选择,或者如果您觉得需要在列表中再添加一个,请自行设计。

【讨论】:

  • XSLT 是我认为必须存在并服务于这个目的的工具。唯一的事情是它反转了我正在寻找的依赖关系。 XSLT 似乎使用 XSL 来定义结果并查询数据以了解如何自我膨胀,而我正在寻找数据来定义大部分布局并让与 XSL 等效的数据膨胀。除非其他人可以提供完美解决我的问题的工具,否则我会接受您的回答,因为它可能是最接近的。
  • 我添加了使用 XSLT 3.0 简化样式表的示例,以显示它与您建议的语法有多么相似。
猜你喜欢
  • 2015-06-17
  • 1970-01-01
  • 2019-04-04
  • 2013-01-07
  • 2015-06-23
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
相关资源
最近更新 更多