goog.string is overridden when I use soyutils.js

﹥>﹥吖頭↗ 提交于 2020-01-05 12:11:14

问题


goog.string is not able to be used when soyutils.js is included in the same HTML file.

because in soyutils.js has its own goog.string that completely override goog.string <-- goog.require('goog.string').


<!DOCTYPE html>
<html>
<head>
    <title>codeBox</title>
    <script src="{{STATIC_URL}}closure-library/closure/goog/base.js"></script>
    <script>

    goog.require('goog.string');

    </script>

    <script src="{{STATIC_URL}}soyutils.js"></script>
</head>
<body>
    <script>
    console.log(goog.string.trim);

    </script>
</body>

(ignore {{STATIC_URL}} that is for Django Server)

console.log(goog.string.trim) will show you "undefined".

That's becuase goog.string is overridden by goog.string located in soyutils.js.

how can i get around this problem without compiling ? (when I compile all the files .. then it runs well)


回答1:


Instead of

<script src="{{STATIC_URL}}soyutils.js"></script>

use

<script src="{{STATIC_URL}}soyutils_usegoog.js"></script>

You can find soyutils_usegoog.js in the same directory as soyutils.js in the closure templates tarball.

The problem arises because there are two versions of soyutils.

  1. soyutils.js is the version for non-closure users and includes just enough closure to make the JavaScript from SoyToJSCompiler work.
  2. soyutils_usegoog.js is the version that works with the closure library and closure compiler. It should not conflict with closure library.

Closure Template JavaScript Usage explains:

JavaScript code that's generated by the template compiler depends on a number of utilities.

Include one of these two utility files, depending on whether you're already using the Closure Library:

  • javascript/soyutils.js
  • javascript/soyutils_usegoog.js

These files are included in the tarball you can download from the Closure Templates downloads page.

If your project already uses the Closure Library, use soyutils_usegoog.js, which is a much smaller file than soyutils.js.




回答2:


Also just want to add to above answer if you are using google closure library then you might need to add

base.js

then

goog.require('goog.string.StringBuffer');
goog.require('goog.soy.data');

then

soyutils_usegoog.js



来源:https://stackoverflow.com/questions/8139945/goog-string-is-overridden-when-i-use-soyutils-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!