【问题标题】:Browser-Side templates with src带有 src 的浏览器端模板
【发布时间】:2023-03-18 13:08:01
【问题描述】:

最近我一直在探索Backbone,他们确实鼓励使用模板引擎。

现在,我有一堆要显示的 html 文件,而且我很可能必须在开发阶段经常编辑它们。我读过的大多数教程都是这样推荐的:

<script type="text/template" id="template1">
    <ul>
        <li>Hic sunt dracones</li>
    </ul>
</script>
<script type="text/javascript">
    template = $('#template1').html();
<script>

所以我想知道这是否可以与src-attribute 一起使用以包含模板文件。或者,如果不是,加载模板文件的常用方法是什么?

【问题讨论】:

    标签: jquery html templates backbone.js


    【解决方案1】:

    使用src 是不可能的。 您可以包含一个 JavaScript 文件,该文件是在服务器上从单独的模板文件生成的;使用 PHP 就可以这么简单:

    <?php
    $templates = array(
        'foo' => file_get_contents('foo.html'),
        'bar' => file_get_contents('bar.html'),
    );
    header('Content-type: text/javascript');
    echo 'var templates = ' . json_encode($templates);
    ?>
    

    使用&lt;script&gt; 标记加载此文件,然后为您提供一个对象templates,您可以在其中通过templates.footemplates.bar 等访问各种模板。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-26
      • 2012-03-18
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      • 2012-03-02
      相关资源
      最近更新 更多