我有一个返回数组的javascript use-api文件。 重要的是要知道这个js用于其他HTML,这就是为什么我不能将代码放在html上
这样的事情(myfile.js
):
"use strict";
var global = this;
use(function() {
var myArray = [];
//something to fill the array with custom objects and inner arrays
return myArray;
});
然后在我的HTML中我有一些代码,但最重要的是我需要在javascript中使用这个数组,但我无法弄清楚如何做到这一点,因为如果我使用context='scriptString'
或{ {1}}它无法正常工作,我无法使用数组。
这是代码:
context='scriptToken'
有没有办法使用这个数组(不修改<div data-sly-use.test="myfile.js">
<!-- some html irrelevant code -->
<script type='text/javascript'>
//this returns a flat string representation of the first level of the array
var a = '${test @context='scriptString'}';
//this give an error in the code
var b = ${test @context='scriptString'};
//this returns empty
var c = '${test @context='scriptToken'}';
</script>
</div>
文件)
答案 0 :(得分:0)
我建议如果你想将变量放入数组中,你只需使用以下内容(并坚持使用纯粹的javascript:
<div data-sly-use.test="myfile.js">
<script type='text/javascript'>
var a = myArray[n];
</script>
</div>
其中n等于数组中要返回值的对象编号。
这样您就不需要编辑javascript文件了,它使一切变得更加简单!
答案 1 :(得分:0)
我自己做了测试,但效果很好。这就是我的所作所为 请注意,这是在AEM 6.1(没有SP1)
的test.html:
<div data-sly-use.test="test.js">
<script type="text/javascript">
var test = [${test @context="scriptString"}];
</script>
This is a TEST!
</div>
<div class="clearfix"></div>
test.js:
"use strict";
use(["/libs/wcm/foundation/components/utils/AuthoringUtils.js"], function (AuthoringUtils) {
return [0,1,2,3,4,5];
});
这是由此产生的html
<div class="test">
<div>
<script type="text/javascript">
var test = [0,1,2,3,4,5];
</script>
This is a TEST!
</div>
<div class="clearfix"></div>
</div>
答案 2 :(得分:0)
听起来你有一个JS对象,在这种情况下是数组,你想在服务器端和客户端使用它。您使用Use-API在服务器端构建并使用它,但是您需要在明亮的模板中使用它,然后您尝试将同一个对象添加到<script>
标记,以便客户端也可以使用它。它是否正确?如果是这样,那么尝试其中之一,如果你还没有
<div data-sly-use.test="myfile.js">
<!-- some html irrelevant code -->
<script type='text/javascript'>
//scriptToken context, no quotation marks
var b = ${test @context='scriptString'};
//unsafe context, hope you trust the source of this object!
var c = ${test @context='unsafe'};
</script>
</div>
但是,如果您不需要服务器端的JS对象,那么就不需要使用Use-API。只需创建一个单独的文件,将javascript添加到页面中,并将其包含在需要它的文件中。
/apps/path/to/shared/myfile.html
<script type="text/javascript">
var global = this;
var myArray = [];
//something to fill the array with custom objects and inner arrays
//etc.
</script>
然后需要JS的模板只包含它
<div>
<!-- some html irrelevant code -->
<sly data-sly-include="path/to/shared/myfile.html"></sly>
</div>