Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a global view in Phoenix Framework?

If I want to create a module with functions that can be accessed in every template and in which I can use all the functions of the view (creating tags, using router paths and etc), what is the best way to achieve that?

Simply put, how do I create a global view?

like image 753
NoDisplayName Avatar asked Sep 24 '15 07:09

NoDisplayName


1 Answers

You can define a module (I'd put it in the helpers directory) that has your functions in it:

defmodule MyApp.SomeHelper do

  def some_function do
    #...
  end

end

You can then include it in MyApp.Web under the view function:

  def view do
    quote do
      use Phoenix.View, root: "web/templates"

      # Import convenience functions from controllers
      import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]

      # Import URL helpers from the router
      import MyApp.Router.Helpers

      # Use all HTML functionality (forms, tags, etc)
      use Phoenix.HTML

      # Import custom helpers
      import MyApp.SomeHelper
    end
  end

The some_function function will now be available in all templates.

like image 99
Gazler Avatar answered Oct 01 '22 02:10

Gazler