elixir-tools / tableau

Static Site Generator
MIT License
154 stars 9 forks source link

Full Attributes for HTMLConverter.convert #99

Closed andyl closed 4 days ago

andyl commented 5 days ago

I'm experimenting with MDEx 2.0 & expanding liquid tags in the markdown. I can't figure out how to expose the data/site assigns to the HTMLConverter.convert function.

Firstly I wrote a converter module to handle liquid tags - this seems to work fine:

defmodule Tableau.MdexConvert do

  @moduledoc false

  def liquid_tags(markdown, assigns) do

    str_assigns = assigns |> stringify_keys()

    markdown
    |> MDEx.parse_document!()
    |> MDEx.traverse_and_update(fn
      # render each text as liquid template
      {node, attrs, children} ->
        children =
          Enum.reduce(children, [], fn
            child, acc when is_binary(child) ->
              with {:ok, template} <- Solid.parse(child),
                   {:ok, rendered} <- Solid.render(template, str_assigns) do
                [to_string(rendered) | acc]
              else
                _ -> [child | acc]
              end

            child, acc ->
              [child | acc]
          end)
          |> Enum.reverse()

        {node, attrs, children}
    end)
  end

  defp stringify_keys(map) do
    Map.new(map, fn {k, v} -> {Atom.to_string(k), v} end)
  end

end

Secondly I modified the HTMLConvert modules to handle liquid tags. This works fine with one problem. The attrs contain the markdown frontmatter variables, but not the site's data or site assigns.

defmodule Tableau.PageExtension.Pages.HTMLConverter do
  @moduledoc false
  def convert(_filepath, body, attrs, _opts) do

    {:ok, config} = Tableau.Config.new(Map.new(Application.get_env(:tableau, :config, %{})))

    body
    |> Tableau.MdexConvert.liquid_tags(attrs)
    |> MDEx.to_html!(config.markdown[:mdex])
  end
end

@mhanberg can you point out how to expose the site/data assigns in the HTMLConvert modules? TIA

mhanberg commented 5 days ago

Unfortunately I'm messing with this part of the codebase as we speak, but fortunately it should make this easier to achieve I believe

Also, nitpick, its MDEx v0.2.0, not v2.0 😂

mhanberg commented 5 days ago

Also for posterity, the "attrs" for these functions are the yaml front matter. Its poorly named and part of what I'm changing at the moment.

andyl commented 5 days ago

Thanks for the note I'll wait for your change. LOL and thanks for the fix re: v0.2.

mhanberg commented 4 days ago

Okay I have this working locally, the converter module will get the full assigns.

Here is a proof of concept showing a custom converter for "Djot" markup files and it has some eex in it to prove it gets the full assigns that other templates get

CleanShot 2024-10-10 at 10 01 43@2x CleanShot 2024-10-10 at 10 03 12@2x

andyl commented 4 days ago

NICE!!