Packages

SEO optimization tools for Phoenix and Phoenix LiveView applications

Current section

Files

Jump to
phoenix_seo_tools lib components head.ex
Raw

lib/components/head.ex

defmodule PhoenixSEOTools.Components.Head do
@moduledoc """
Phoenix component for rendering SEO-related elements in the HTML head.
This component renders meta tags, JSON-LD structured data, and link tags
that have been generated by the `PhoenixSEOTools.SEO` module.
## Usage
Add this component to your root layout:
```heex
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<.meta meta={@meta} page_title={@page_title} />
<!-- other head elements -->
</head>
```
The `meta` assign is expected to come from the `PhoenixSEOTools.SEO.build_meta/2` function.
"""
use Phoenix.Component
alias PhoenixSEOTools.PageLink
alias PhoenixSEOTools.PageMeta
@doc """
Renders SEO-related meta tags, JSON-LD structured data, and link tags.
## Attributes
* `page_title` - The title of the page (optional, will use `meta.page_title` if not provided)
* `meta` - A map containing SEO metadata, typically coming from `PhoenixSEOTools.SEO.build_meta/2`
* `:page_title` - The title of the page
* `:metas` - A list of `PhoenixSEOTools.PageMeta` structs
* `:schemas` - A list of JSON-LD structured data maps
* `:links` - A list of `PhoenixSEOTools.PageLink` structs
## Examples
```heex
<.meta meta={@meta} page_title={@page_title} />
```
"""
attr(:page_title, :string)
attr(:meta, :map, default: %{})
def meta(assigns) do
~H"""
<.live_title>
{@page_title || @meta[:page_title] || ""}
</.live_title>
<%= for %PageMeta{} = page_meta <- Map.get(@meta, :metas, []) do %>
<meta
name={page_meta.name}
hid={page_meta.name}
property={page_meta.name}
content={page_meta.content}
/>
<% end %>
<%= for schema <- Map.get(@meta, :schemas, []) do %>
<script type="application/ld+json">
<%= Phoenix.HTML.raw Jason.encode!(schema) %>
</script>
<% end %>
<%= for %PageLink{} = page_link <- Map.get(@meta, :links, []) do %>
<link rel={page_link.rel} href={page_link.href} />
<% end %>
"""
end
end