<script> 标记中的未定义函数 static_path/2

Undefined function static_path/2 in <script> tag

我正在使用嵌入式 Elixir 进行模板化 HTML。

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

这一行给我以下错误:

== Compilation error in file lib/chat_web/views/layout_view.ex ==
** (CompileError) lib/chat_web/templates/layout/app.html.eex:24: undefined function static_path/2
(elixir 1.10.2) src/elixir_locals.erl:114: anonymous fn/3 in : 
:elixir_locals.ensure_no_undefined_local/3
(stdlib 3.12.1) erl_eval.erl:680: :erl_eval.do_apply/6
(elixir 1.10.2) lib/kernel/parallel_compiler.ex:304: anonymous fn/4 in 
Kernel.ParallelCompiler.spawn_workers/7

static_path函数来自YourAppWeb.Router.Helpers(在Phoenix 1.4之前,它来自YourApp.Router.Helpers),但重要的是在1.4之前,views会import YourApp.Router.Helpers ,从而使其在您的视图和模板中可用,但从 1.4 开始,视图 alias YourAppWeb.Router.Helpers, as: Routes(您可以在应用程序的 web.ex 文件中验证这一点),因此您可以使用 Routes.<function>.

因此,正如我在评论中所建议的那样,您的示例应该适用于:

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