Pages

Pages, along with components, are the fundamental building blocks of a Hologram application. Each page represents a distinct route in your application and contains both the UI template and the business logic.

Basic Example

Here's a minimal page implementation:

defmodule MyApp.HelloWorldPage do
  use Hologram.Page
  
  route "/hello-world"
  
  layout MyApp.MainLayout

  def template do
    ~H"""
    <div>Hello World!</div>
    """
  end
end

Routing and Parameters

Pages must define their URL route using the route/1 macro.

Routes can be static:

route "/products"

or contain dynamic parameters:

route "/users/:username/posts/:post_id/comments"

For routes with parameters, use the param/2 macro to specify how string parameters should be converted:

param :username, :string
param :post_id, :integer

Supported parameter types:

Initialization

The init/3 callback is called when the page is first loaded. It receives three parameters:

The function should return either:

Example:

def init(params, component, _server) do
  component
  |> put_state(:counter, 0)
  |> put_state(:user_id, params.user_id)
end

Template

Pages must define a template using either:

Example using function:

def template do
  ~H"""
  <div>Hello World!</div>
  """
end

See the Template Syntax documentation for more details.

Event Processing

Pages can handle user interactions and business logic through two mechanisms:

Basic example:

def action(:increment, params, component) do
  put_state(component, :count, component.state.count + params.by)
end

def command(:insert_user, params, server) do
  {:ok, user} = Repo.insert(%User{first_name: params.first_name})
  put_action(server, :user_inserted, user: user)
end

See the Actions and Commands documentation for more details.