在Phoenix Framework应用程序中的某些页面上包含Javascript [英] Include Javascript on Certain Pages in Phoenix Framework Application
问题描述
我有一些Javascript,我只想包含在我的Phoenix应用程序的某些页面上。
I've got a bit of Javascript that I only want to include on certain pages in my Phoenix application.
现在我的Javascript里面有一个Javascript脚本标记在 myapp / web / templates / post / form.html.eex
。
Right now I've got the Javascript inside a script tag in myapp/web/templates/post/form.html.eex
.
我明白我可以将JavaScript移动到 web / static / js / app.js
...但我不想在每个页面上包含Javascript(仅在2个特定页面上需要) )。
I understand that I can move the JavaScript to web/static/js/app.js
...but I don't want to include the Javascript on every page (it's only required on 2 specific pages).
在我的应用程序的某些页面上加载此部分Javascript而不重复代码并违反DRY原则的最佳方法是什么?
What's the best way to load this section of Javascript on certain pages in my application without duplication the code and violating the DRY principle?
推荐答案
1。
将所有javascript从中删除form.html.eex 到自己的文件中(可能类似 js / posts.js )。
1.
Put all that javascript from form.html.eex into its own file (maybe something like js/posts.js).
在此处添加底部:
export var Post = { run: function() {
// put initializer stuff here
// for example:
// $(document).on('click', '.remove-post', my_remove_post_function)
}}
2.
在 app.html 中,< script src =#{static_path(@ conn,/ js / app.js)}>< / script>
添加:
<%= render_existing @view_module, "scripts.html", assigns %>
3.
然后,在你的查看(可能 views / post_view.ex ),添加如下方法:
3.
Then, in your view (probably views/post_view.ex), add a method like this:
def render("scripts.html", _assigns) do
~s{<script>require("web/static/js/posts").Post.run()</script>}
|> raw
end
结论
现在只有在使用帖子视图时才会加载javascript文件 post.js 。
这篇关于在Phoenix Framework应用程序中的某些页面上包含Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!