首页 > 解决方案 > 如何从页面的 javascript 文件而不是 html 中访问预编译的 Handlebars 模板?

问题描述

我有一个terrain.html 文件和一个terrain.js。我已经预编译了一个车把模板(templates/favorites.precompiled.js)。我正在尝试在terrain.js 文件中引用收藏夹模板,以便可以注入上下文,然后将其附加到ID 为“输出”的容器中。

我可以在 HTML 中很好地访问模板,但我无法弄清楚我需要做什么才能从 terrain.js 文件中引用它。

    <script src="scripts/terrain.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.runtime.js"></script>
    <script id="favorites-template" src="partials/favorites.precompiled.js"></script>

            <div id="output">

            </div>

            <script>
                console.log(Handlebars.templates)
            </script>

这会按预期输出:{favorites: ƒ}

但是,如果我尝试在 terrain.js 中将 Handlebars.templates 打印到控制台,我会得到未定义。我也尝试过指定特定的模板 Handlebars.templates['favorites'] 和 Handlebars.templates['templates/favorites.precompiled'] 等。

标签: javascripthtmlhandlebars.jstemplating

解决方案


推荐阅读