Phoenix.View

Serves as the base view for an entire Phoenix application view layer

Users define App.Views and use Phoenix.View. The main view:

Examples

defmodule App.Views do
  defmacro __using__(_options) do
    quote do
      use Phoenix.View, templates_root: unquote(Path.join([__DIR__, "templates"]))
      import unquote(__MODULE__)

      # This block is expanded within all views for aliases, imports, etc
      def title, do: "Welcome to Phoenix!"
    end
  end

  # Functions defined here are available to all other views/templates
end

defmodule App.PageView
  use App.Views

  def display(something) do
    String.upcase(something)
  end
end

Summary

default_templates_root()

Returns the default String template root path for current mix project

render(module, template, assigns)

Renders template to String

template_path_from_view_module(view_module, templates_root)

Finds the template path given view module and template root path

unwrap_rendered_content(content, arg2)

Unwraps rendered String content within extension specific structure

Functions

default_templates_root()

Returns the default String template root path for current mix project

render(module, template, assigns)

Renders template to String

  • module - The View module, ie, MyView
  • template - The String template, ie, “index.html”
  • assigns - The Dictionary of assigns, ie, [title: "Hello!"]

Examples

iex> View.render(MyView, "index.html", title: "Hello!")
"<h1>Hello!</h1>"

Layouts

Template can be rendered within other templates using the within option. within accepts a Tuple, of the form {LayoutModule, "template.extension"}

When the sub template is rendered, the layout template will have an @inner assign containing the rendered contents of the sub-template. For html templates, @inner will be passed through Html.safe/1 automatically.

Examples

iex> View.render(MyView, "index.html", within: {LayoutView, "app.html"})
"<html><h1>Hello!</h1></html>"
template_path_from_view_module(view_module, templates_root)

Finds the template path given view module and template root path

Examples

iex> Phoenix.View.template_path_from_view_module(MyApp.UserView, "web/templates")
"web/templates/user"
unwrap_rendered_content(content, arg2)

Unwraps rendered String content within extension specific structure

Examples

iex> View.unwrap_rendered_content({:safe, "<h1>Hello!</h1>"}, ".html")
"<h1>Hello!</h1>"
iex> View.unwrap_rendered_content("Hello!", ".txt")
"Hello!"