【问题标题】:Rendering mustache template stored in file渲染存储在文件中的胡子模板
【发布时间】:2013-08-29 13:21:04
【问题描述】:

我正在一个 Rails 应用程序中尝试通过一个 mustache 模板呈现一些 json 数据。

我的出发点是这个 railscast:http://railscasts.com/episodes/295-sharing-mustache-templates

在演员阵容中,Rayn 做了类似的事情

$('#target').append Mustache.to_html($('#project_template').html(), json-data)

在 html 中有一个 id="project_template" 的 div,其中包含模板

<script type="text/html" id="project_template">
 ...
</script>

但是,我希望能够将 mustache 模板存储到一个文件中(比如说在 app/views/projects/project.mustache 中)并直接在我的 js 中加载它。 类似的东西

$('#target').append Mustache.xxxxx(MUSTACHE_FILE, json-data)

我环顾四周,但找不到任何可行的方法或任何建议。这有可能实现吗?

谢谢。

【问题讨论】:

    标签: javascript ruby-on-rails mustache


    【解决方案1】:

    您不能直接在 javascript 中访问服务器端文件,但您可以使用另一种方式将模板存储在服务器端。

    例如,您可以将模板存储在app/views/projects/project.mustache 中。

    在你的project.mustache中,你可以写:

    <script type="text/html" id="project_template">
     ...
    </script>
    

    在您看来,您可以使用:

    <%= render :file => 'projects/project.mustache' %>
    

    并像以前一样使用javascript。

    $('#target').append(Mustache.to_html($('#project_template').html(), json-data));
    

    我认为它并不完美,但它应该可以工作:)

    【讨论】:

    • 这正是 railscast 所做的。我正在寻找一种不同的方法。顺便谢谢。
    • 哦,对不起,我没有看演员表,因为它是专业演员,否则我不会提交这个答案。在您的问题中,您似乎想通过javascript获取服务器端模板的内容,这比这个解决方案复杂得多:)
    猜你喜欢
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2021-12-13
    • 2016-06-07
    相关资源
    最近更新 更多