Created
February 23, 2025 19:27
-
-
Save jdmarshall/563c8612ce3c78ff612ace30bd0c5cf7 to your computer and use it in GitHub Desktop.
Example working with mdex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def markdown(assigns) do | |
body = | |
case (assigns.value) do | |
nil -> assigns.fallback | |
_ -> anchors_with_targets(assigns.value) | |
end | |
~H""" | |
<div class={["markdown", @class]}> | |
<%= body %> | |
</div> | |
""" | |
end | |
defp anchors_with_targets(markdown) do | |
opts = [ | |
render: [unsafe_: true, escape: true] | |
] | |
parsed = case MDEx.parse_document(markdown, opts) do | |
{:ok, parsed} -> parsed | |
{:error, err} -> | |
IO.inspect(err) | |
"Syntax Error" | |
end | |
doc = parsed | |
|> MDEx.traverse_and_update(fn | |
%MDEx.Link{} = link -> | |
body = MDEx.to_html!(link.nodes) | |
literal = "<a title=\"#{link.title}\" href=\"#{URI.encode(link.url)}\" target=\"_blank\">#{body}</a>" | |
%MDEx.Raw{literal: literal} | |
node -> | |
node | |
end) | |
case MDEx.to_html(doc) do | |
{:ok, escaped} -> Phoenix.HTML.raw(escaped) | |
{:error, err} -> | |
IO.inspect(err) | |
"Syntax Error" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment