Skip to content

Latest commit

 

History

History
123 lines (74 loc) · 2.83 KB

7.template_variables_and_helper_functions.md

File metadata and controls

123 lines (74 loc) · 2.83 KB

Template variables and helper functions

Global variables

  • @site_params: you can access to all data that you define in site_params.exs from this variable

  • @conn hold all data of current connection to server include: host, port, params, etc. You can read more here

Example

<h1><%= @site_params.title %></%></h1>
<h3><%= @site_params.sub_title %></%></h>

Template specific variables

post/single.html.eex

  • @post: current post struct

post/list.html.eex

  • @posts: list of post for current page
  • @paginator: a struct which hold pagination data

page/page.html.eex

  • @page: current page struct

category/single.html.eex

  • @category: current category struct
  • @posts: list of posts for current category
  • @paginator: a struct which hold pagination data

category/list.html.eex

  • @items: list of item with category data

    item format:

    %{
    		category: <Category>,
    		post_count: <Integer>
    }
  • tag/single.html.eex

    • @tag: current tag struct
    • @posts: list of posts for current tag
    • @paginator: a struct which hold pagination data

    tag/list.html.eex

    • @items: list of item with tag data

      item format:

      %{
      		tag: <Tag>,
      		post_count: <Integer>
      }

Paginator struct

This struct is available for every listing page via variable @paginator. It presents pagination data for listing query.

%Paginator{
	entries: <list of item>,
	page: <Integer>, # starting from 1
	size: <Integer>, # number of entry per page
	total_page: <Integer>,
	entry_count: <Integer>, # total entry count on database
	has_next?: <Boolean>,
	has_prev?: <Boolean>
}

Helper functions

These functions a available in all template

  • partial(template_name, assigns) render a template in partial directory

    Example: partial('feature_post_widget.html', assigns)

  • next_page_path(Plug.Conn, Paginator) and preve_page_path(Plug.Conn, Paginator) get the next/previous page path from paginator

    Example:

    <%= if @paginator.has_next? do %>
      <%= next_page_path(@conn, @paginator) %>
    <% end %>
  • compile_shortcode(html_string, assigns) receive an input string and compile all shortcode in that string. This function is call before rendering a post to compile all shortcode in post content.

    Example:

    <%= compile_shortcode(@post.content, assigns) %>
    
  • format_date(date, format_str) format a date struct to a string using Timex library. Learn format directive here.

    Example: format_date(@post.date, '{0M}/{0D}/{YYYY}) to format publish date mm/dd/yyyy