【问题标题】:Rendering static HTML in Meteor/Blaze在 Meteor/Blaze 中渲染静态 HTML
【发布时间】:2015-05-09 12:53:17
【问题描述】:

我一直试图在 Meteor / Telescope (telesc.pe) 应用程序中包含静态 HTML+JavaScript,但无法使用 Blaze 进行操作。

为了创建一个比我的原始案例更简单的案例,我尝试在下面的通过 Meteor 中插入一个简单的 HTML + javascript 代码块(非常基本的 D3.js 可视化创建一个圆圈)。这个 HTML 块存储在 MongoDB 的集合中,并使用下面的模板访问

<script type="text/javascript" src="http://mpld3.github.io/js/mpld3.v0.2.js"></script>
  <h1>Circle</h1>
    <div id="viz"></div>
  <h1>/Circle</h1>
    <script type="text/javascript">

    var sampleSVG = d3.select("#viz")
        .append("svg")
        .attr("width", 100)
        .attr("height", 100);

    sampleSVG.append("circle")
        .style("stroke", "gray")
        .style("fill", "white")
        .attr("r", 40)
        .attr("cx", 50)
        .attr("cy", 50)
        .on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
        .on("mouseout", function(){d3.select(this).style("fill", "white");});

    </script>

我一直将它作为非转义标签包含在 Meteor 中。例如

<template name="post_body">
  {{{ htmlBody }}}
</template>

上面 sn-p 中的 HTML 正确呈现(文本 Circle 和 /Circle),但它似乎没有尝试加载我包含的任何 javascript 元素。

我完全知道这不是将可视化加载到 Meteor 应用程序的最佳方式,但很可能需要这样做,因为我正在使用的(更复杂的)可视化是使用外部静态生成的应用程序。

任何有关如何使这项工作的帮助将不胜感激!

【问题讨论】:

    标签: meteor meteor-blaze spacebars


    【解决方案1】:

    你不能在 Meteor 模板中使用 &lt;script&gt; 标签。 Meteor 会解析您的模板以将其作为 DOM 对象呈现到 DOM 中,并且不执行任何内联 JavaScript。

    也就是说,实现你想要做的事情很容易。首先,走这条线:

    <script type="text/javascript" src="http://mpld3.github.io/js/mpld3.v0.2.js"></script>
    

    并将其放在您的 index.html 文件的 &lt;head&gt; 中,或者任何作为您应用入口点的 HTML 文件中。

    接下来,将内联 script 块中的代码放入模板的 rendered 回调中:

    Template.post_body.rendered = function() {
        var sampleSVG = d3.select("#viz")
            .append("svg")
            .attr("width", 100)
            .attr("height", 100);
    
        sampleSVG.append("circle")
            .style("stroke", "gray")
            .style("fill", "white")
            .attr("r", 40)
            .attr("cx", 50)
            .attr("cy", 50)
            .on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
            .on("mouseout", function(){d3.select(this).style("fill", "white");});
    };
    

    它会在模板被渲染到 DOM 后执行,如你所愿。为了提高性能,您可以考虑在rendered 中将d3.select 替换为this.findthis.findAll,以将DOM 搜索限制在模板上下文中。见http://docs.meteor.com/#/full/template_find

    如果你是直接从你的数据库中处理一个糟糕的 HTML 块,它有你的示例中的 &lt;script&gt; 标签,你需要首先将它解析为一个字符串。使用正则表达式查找第一个 script 标记的 src(我会让您找到许多其他关于如何做到这一点的 SO 答案)并使用 jQuery 的 $.getScript 动态加载该脚本。使用另一个正则表达式提取内联脚本块,并将其作为回调传递给$.getScript。尽管我讨厌这样说,但你必须使用eval

    Template.post_body.rendered = function() {
        $.getScript(urlThatYouParsed, function() { eval(codeThatYouParsed); });
    };
    

    【讨论】:

      猜你喜欢
      • 2016-03-10
      • 1970-01-01
      • 2014-05-09
      • 2017-11-16
      • 2016-04-30
      • 1970-01-01
      • 2014-02-14
      • 2014-09-27
      • 1970-01-01
      相关资源
      最近更新 更多