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:
- :atom - converts to atom
- :float - converts to float
- :integer - converts to integer
- :string - keeps the parameter as string
Initialization
The init/3
callback is called when the page is first loaded. It receives three parameters:
params
- a map containing the URL parameters after type conversioncomponent
- a struct representing the client-side state containerserver
- a struct representing the server-side state container
The function should return either:
- A tuple
{component, server}
when modifying both client and server state - Just the
component
struct when only modifying client state - Just the
server
struct when only modifying server state
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:
- A
template/0
function with~H
sigil - A colocated .holo template file
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:
- Actions: client-side operations that update local state
- Commands: server-side operations that can perform remote tasks
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.