Corex.Code (Corex v0.2.0)

View Source

Displays syntax-highlighted code with Makeup.

Installation

Add makeup and the lexer packages for each language you use:

defp deps do
  [
    {:makeup, "~> 1.2"},
    {:makeup_elixir, "~> 1.0.1 or ~> 1.1"},
    {:makeup_html, "~> 1.0"},
    {:makeup_css, "~> 1.0"},
    {:makeup_js, "~> 1.0"}
  ]
end

Only makeup is required. Add the lexer packages you need; without a lexer, code renders as plain escaped text.

Security

Highlighted output is injected with Phoenix.HTML.raw/1. Treat the code attr as trusted (developer-authored or sanitized). Do not pass untrusted user input — an HTML-capable Makeup lexer can emit markup into the page.

Anatomy

Basic Usage

<.code code="def hello, do: :world" />

Multi-line with heredoc

Use """ heredoc for readable multi-line code in templates:

<.code code={"""
defmodule Hello do
  def world, do: "Hello, World!"
end
"""} />

Loading from a file

<.code code={File.read!("priv/code_examples/example.ex")} language={:elixir} />

Or in a controller, load the file and pass the contents:

def my_page(conn, _params) do
  code = File.read!("priv/code_examples/example.ex")

  render(conn, :my_page, code: code)
end
<.code code={@code} language={:elixir} />

The language attribute maps to Makeup's registry (e.g. :elixir"elixir"). Add the corresponding lexer package to your deps for each language. Without it, code renders as plain escaped text.

Style

Use data attributes to target elements:

[data-scope="code"][data-part="root"] {}
[data-scope="code"][data-part="content"] {}

With Corex Design, syntax highlighting styles are included in code.css. Nothing else is required.

Axes: Size (text-smtext-xl, or ui-size-*), Radius (ui-rounded-*), Max width (code--max-w-* / max-w-*). See the modifier guide.

Without Corex Design, run mix corex.design.code to generate the Makeup stylesheet and import it in your CSS:

mix corex.design.code
mix corex.design.code assets/styles/syntax.css
mix corex.design.code --force
@import "./code_highlight.css";

Summary

Components

code(assigns)

Attributes

  • code (:string) (required) - The raw source code to display.
  • language (:atom) - The language name in Makeup's registry (e.g. :elixir, :html). Add the lexer package to deps; otherwise renders as plain escaped text. Defaults to :elixir.
  • inline (:boolean) - Whether to display the code inline. Defaults to false.
  • Global attributes are accepted.