My space on the web https://inhji.de
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

38 lines
1.0 KiB

defmodule Mirage.Markdown do
import Phoenix.HTML.Link, only: [link: 2]
import Phoenix.HTML, only: [raw: 1, safe_to_string: 1]
import Ecto.Changeset, only: [get_change: 2, put_change: 3]
def maybe_render_markdown(changeset, markdown_field, html_field) do
if markdown = get_change(changeset, markdown_field) do
html = render(markdown)
put_change(changeset, html_field, html)
else
changeset
end
end
@crossref_regex ~r/\[\[(?<id>\d+)\]\]/
def render(markdown) do
options = %Earmark.Options{
code_class_prefix: "lang- language-"
}
@crossref_regex
|> Regex.scan(markdown, capture: :all_but_first)
|> List.flatten()
|> Enum.reduce(markdown, fn note_id, markdown ->
case Mirage.Notes.get_note(note_id) do
nil ->
markdown
note ->
a_element = link(note.title, to: "/notes/#{note.id}") |> safe_to_string()
String.replace(markdown, "[[#{note_id}]]", a_element)
end
end)
|> Earmark.as_html!(options)
end
end