Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

elixir - Phoenix additional layout variables like @inner

I am looking to add additional layout parameters like the @inner for the layout. For example @title for the <title>@title</title> and an area for onload javascript for individual pages.

window.onload = function () {
   @onload_js
}

These are set in the layout, so I am not sure the best way to handle these in Phoenix. Thanks :D.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For the page title, you can simply pass a value through from your controller:

def edit(conn, params) do
  render(conn, "edit.html", page_title: "Edit The Thing")
end

<head>
  <title><%= assigns[:page_title] || "Default Title" %></title>
</head>

Note that this uses assigns[:page_title] instead of @page_title or assigns.page_title as they will error if the :page_title key is not present in assigns.


For including templates (your script example) there is render_existing/3 (and the docs for the same function in the latest version of Phoenix).

The documentation gives a similar example to what you requested so I have copied it here for convenience:

Consider the case where the application layout allows views to dynamically render a section of script tags in the head of the document. Some views may wish to inject certain scripts, while others will not.

<head>
  <%= render_existing view_module(@conn), "scripts.html", assigns %>
</head>

Then the module for the @inner view can decide to provide scripts with either a precompiled template, or by implementing the function directly, ie:

def render("scripts.html", _assigns) do
  "<script src="...">"
end

To use a precompiled template, create a scripts.html.eex file in the templates directory for the corresponding view you want it to render for. For example, for the UserView, create the scripts.html.eex file at web/templates/user/.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...