Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require a JavaScript module inside a single Phoenix template

What is the standard method to require a defined JavaScript module inside of a single Phoenix Template?

I don't want the module required anywhere but inside this one template.

Here is a snippet of the files I am using.

web/static/js/trend_chart.js

let TrendChart = {
  //... some JS module code here
}

web/templates/layout/app.html.eex

This has the standard app load/require.

...

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

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

...

web/templates/page/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 -->

Update #1

I'm really looking for a way to have two @inner blocks in the main layout. One for the content, and one for additional JavaScript items to be loaded after the content.

Something like sections in ASP.NET MVC. (I know, I know!)

So the app.html.eex would end up something like this:

...
@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*
like image 672
John Long Avatar asked Jul 11 '15 14:07

John Long


1 Answers

You can save the file to web/static/assets/trend_chart.js then it will be copied to priv/static/trend_chart.js and available from <script src="<%= static_path(@conn, "/trend_chart.js") %>"></script>.

All files saved to the web/static/assets directory are directly copied to priv/static without going through the build phase.

like image 102
Chris McCord Avatar answered Oct 17 '22 00:10

Chris McCord