【问题标题】:Use ant to wrap html code in static template使用ant将html代码包装在静态模板中
【发布时间】:2011-11-20 19:47:16
【问题描述】:

我有几个 HTML 文件位于不同的位置(在一个共同的根目录中),如下所示:

index.html
moduleA/list.html
moduleA/add.html
moduleB/list.html
moduleB/add.html
...

此外,我还有一个名为 _template.html 的文件,其中包含 HTML 代码和占位符 #CONTENT#。 我需要什么:

  1. 将所有 HTML 文件复制到 public/ 目录
  2. public/ 目录中的每个 HTML 文件还应该包含来自 _template.html 的代码,包裹在原始内容周围。

我使用 ANT 来复制文件,但我不知道如何将模板代码包装在代码周围... 我的 ANT 脚本如下所示:

<project default="build">
    <target name="build">
        <copy todir="${dir.intermediate}/temp">
            <fileset dir="${dir.source}" includes="**/*.html"/>
        </copy>
    </target>
</project>

示例:

index.html

<div>This is the index-page</div>

_template.html

<html>
    <head><title>Page-Title</title></head>
    <body>
        #CONTENT#
    </body>
</html>

应该生成输出文件:

<html>
    <head><title>Page-Title</title></head>
    <body>
        <div>This is the index-page</div>
    </body>
</html>

【问题讨论】:

    标签: ant build-automation


    【解决方案1】:

    使用纯 ant 任务完全可以做到这一点:

    首先使用 loadfile 将“替换”字符串加载到属性中:

    <loadfile property="replacement" srcFile="index.html"/>
    

    然后在复制你的模板之后,最终文件将在哪里执行:

    <replaceregexp file="${my.final.file}"
                   match="#CONTENT#"
                   replace="${replacement}"
    />
    

    就是这样,您的文件现在应该是所需的文件了 :)

    【讨论】:

    • 这仅适用于单个文件。您必须做更多工作才能将所有文件包装在一个文件集中。
    • @matt 这可以是目标的一部分,并且可以使用 ant-contrib foreach 任务多次调用目标。如果你想要一个例子,请告诉我:)
    • 这个方案很有风格,我喜欢!但是,将它应用到许多文件(for-loop + 额外目标)需要额外的脚本,这会使我已经很大的 ant 脚本变得更大,更难维护。
    【解决方案2】:

    如果您想坚持使用内置的 ant 任务,一种可能的解决方法是将模板文件分成两个文件,一个“pre”部分,如下所示:

    <html>
      <head><title>Page-Title</title></head>
      <body>
    

    还有一个像这样的“帖子”部分:

      </body>
    </html>
    

    然后你可以在你的copy 任务中的filterchain 中使用concatfilter

    <copy todir="${dir.intermediate}/temp">
      <fileset dir="${dir.source}" includes="**/*.html"/>
      <filterchain>
        <concatfilter prepend="src/_template_pre.html" append="src/_template_post.html" />
      </filterchain>
    </copy>
    

    如果不使用诸如 ant-contrib 或脚本之类的东西,我看不到任何使用单个模板文件执行此操作的方法。

    【讨论】:

    • 谢谢!该解决方案简单有效。阅读此答案后,我能够在 3 分钟内解决我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    相关资源
    最近更新 更多