【问题标题】:Issue with Closure Template (soy templates) rendering via Javascript & jQuery通过 Javascript 和 jQuery 呈现闭包模板(大豆模板)的问题
【发布时间】:2020-10-29 06:09:28
【问题描述】:

我正在使用 javascript 和 jQuery 来呈现 closure templates(大豆模板)。我正在关注它的 hello world 示例。
我的 jsfiddle here .

example 中所述,以下代码有效,

document.write(soy.examples.simple.helloWorld());

&提供

世界你好!

但是当与 jQuery 一起使用动态插入闭包模板的内容时,它总是返回空,没有附加任何内容。 $('#withoutContent').append(soy.examples.simple.helloWorld());


讽刺的是,进一步看,下面的 jQuery 工作正常

$('#withContent').append(soy.examples.simple.helloWorld().content);


我在从非常旧版本的闭包模板升级时遇到了这个问题。我们有很多这样的模板,在 javascript 中更新每个模板的用法以使用 .content 既麻烦又容易出错。
为什么jQuery不能正确获取模板的内容??

【问题讨论】:

    标签: javascript jquery google-closure-templates soy-templates


    【解决方案1】:

    为什么 jQuery 不能正确获取模板的内容?

    soy.examples.simple.helloWorld() 的调用会返回此对象:

    {
      constructor: function(){goog$soy$data$SanitizedContent.call(this)},
      content: "Hello world!",
      contentDir: null,
      contentKind: { ... },
      getContent: function(){return this.content},
      toString: function(){return this.content}
    }
    

    如您所见,它不是 HTML,它有几个属性和方法 - 其中一个是 toString(),它返回 .content

    document.write() 需要一个字符串参数。如果您传递其他东西(例如上面的对象),那么它将自动为您调用.toString()。这就是为什么

    document.write(soy.examples.simple.helloWorld());
    

    有效。

    jQuery 的$.append() 接受所有类型的东西——纯字符串、单个 DOM 节点、DOM 节点列表、其他 jQuery 对象、函数——并为每个参数类型做适当的事情。但是为了换取这种灵活性,它不会简单地将其参数转换为字符串。一些 jQuery 无法识别的随机对象将被丢弃。这就是为什么

    $('#withoutContent').append(soy.examples.simple.helloWorld());
    

    不起作用。

    更新每个人在 javascript 中的使用以使用 .content 很麻烦且容易出错。

    如果您可以在所有这些位置输入$('...').append(),那么您可以在所有这些位置输入.content

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      相关资源
      最近更新 更多