在单个Phoenix模板中需要JavaScript模块

Joh*_*ong 11 html javascript phoenix-framework

在单个Phoenix模板中需要定义的JavaScript模块的标准方法是什么?

我不希望模块需要在任何地方,但在这个模板中.

这是我正在使用的文件的片段.

网络/静态/ JS/trend_chart.js

let TrendChart = {
  //... some JS module code here
}
Run Code Online (Sandbox Code Playgroud)

网页/模板/布局/ app.html.eex

这有标准的app load/require.

...

<script src="<%= static_path(@conn, "/js/app.js") %>"></script>

<script>require("web/static/js/app")</script>

...
Run Code Online (Sandbox Code Playgroud)

网页/模板/页/ index.html.eex

<!-- what do i put in this template to require / load the TrendChart module code? -->
<!-- i don't want it required globally, so i don't want to put it in the app.html.eex file -->
Run Code Online (Sandbox Code Playgroud)

更新#1

我真的在寻找一种@inner在主布局中有两个块的方法.一个用于内容,另一个用于在内容之后加载其他JavaScript项目.

类似ASP.NET MVC中的部分.(我知道我知道!)

所以最终app.html.eex将会是这样的:

...
@inner
...

<script src="<%= static_path(@conn, "/js/app.js") %>"></script>
<script>require("web/static/js/app")</script>

*something here to load page/template specific javascript*
Run Code Online (Sandbox Code Playgroud)

Chr*_*ord 7

您可以将文件保存到该文件,web/static/assets/trend_chart.js然后将其复制到其中priv/static/trend_chart.js并从中获取<script src="<%= static_path(@conn, "/trend_chart.js") %>"></script>.

保存到web/static/assets目录的所有文件都直接复制到priv/static不经过构建阶段.

  • 这种方法的警告是你没有得到缩小.另一种方法是建立一个规则,如https://github.com/phoenixframework/phoenix/blob/10b989dda6fb2ac38d3e876e32f107294475a156/installer/templates/static/brunch/brunch-config.js#L10供应单一到相同名字本身. (4认同)