matthewsinclair

matthewsinclair

I have a couple of (relative) newb questions about Nimble Publisher that I can’t quite work out.

I have it (more or less) working but two questions remain:

  1. What is the best way to handle a markdown file with an image ref in it? For example, let’s say that the original markdown file was in a directory called dir/ and in that directory is an image called dir/image.png. If the markdown file is in the same directory (ie dir/markdown.md I could use the standard markdown image reference tag ![image](./image.png)and the markdown viewer or renderer would create an <img src="./image.png">… tag from the markdown. However, because of the way that the routes are set up, that image url ends up being interpreted as an id for a blog post, which of course it can’t find. I can’t be the first person to ever try to do this so there must be an idiomatic way to handle URIs embedded in the markdown file or a way to configure the routes so that markdown is handled by nimble by images are and other content are treated as normal urls.

  2. I want to control the way that the HTML is emitted from the markdown processor so that I can style it. At the moment, a markdown # Heading is being rendered simply as <h1>Heading</h1>. But what I need to do is control the styling of the emitted HTML. Again, I can’t be the first person who has ever needed to do this, but I can’t find from the docs what the best way to handle this would be.

Any ideas or even a link to an example or some docs for either problem would be very helpful. Thanks.

PS: I originally posted this on GitHub to the NimblePublisher repo here, but was asked to cross-post here by @josevalim.

Showing Posts 1 to 4

matthewsinclair

matthewsinclair OP

Ok, so for what it’s worth, I changed the standard NimblePublisher Post module to look like this:

defmodule Msdc.Blog.Post do
  @enforce_keys [:blog, :id, :author, :title, :body, :description, :tags, :date, :long_date]
  defstruct [:blog, :id, :author, :title, :body, :description, :tags, :date, :long_date]

  @style_map %{
    "h1" => "text-4xl font-bold tracking-tight text-zinc-800 sm:text-5xl dark:text-zinc-100",
    "h2" => "text-m font-bold text-zinc-800 dark:text-zinc-100",
    "h3" => "text-base font-semibold tracking-tight text-zinc-800 dark:text-zinc-100",
    "h4" => "text-3xl tracking-tight text-zinc-800 sm:text-3xl dark:text-zinc-100",
    "p" => "mt-6 text-base text-zinc-600 dark:text-zinc-400",
    "a" => "text-m font-medium text-teal-500",
    "img" => ""
  }

  def build(filename, attrs, body) do
    [blog, year, _month_day_id_dir, month_day_id] = filename |> Path.rootname() |> Path.split() |> Enum.take(-4)
    [month, day, id] = String.split(month_day_id, "-", parts: 3)
    date = Date.from_iso8601!("#{year}-#{month}-#{day}")
    long_date = Calendar.strftime(date, "%B, %d")
    struct!(__MODULE__, [blog: blog, id: id, date: date, long_date: long_date, body: inject_style(@style_map, body)] ++ Map.to_list(attrs))
  end

  def inject_style(style_map, html_content) do
    Enum.reduce(style_map, html_content, fn {tag, class_str}, acc ->
      regex = ~r/(<#{tag}[^>]*)(>)/
      replacement = "\\1 class=\"#{class_str}\"\\2"
      String.replace(acc, regex, replacement)
    end)
  end

end

The inject_style/2 function is a bit of a mess, but what it does is add a class="…" attribute for each HTML tag it finds in the raw blog post content where the value of the class is taken from the map of HTML elements onto class strings kept in @style_map.

I know that it is far from robust, but as a PoC, it serves my purpose for now.

billylanchantin

billylanchantin

Here’s my approach for 2 (but with your styles substituted).

I’ve added the following to my post.ex:

  def earmark_options do
    Earmark.Options.make_options!(postprocessor: Earmark.AstTools.node_only_fn(&add_tag_class/1))
  end

  @tag_to_class %{
    "h1" => "text-4xl font-bold tracking-tight text-zinc-800 sm:text-5xl dark:text-zinc-100",
    "h2" => "text-m font-bold text-zinc-800 dark:text-zinc-100",
    "h3" => "text-base font-semibold tracking-tight text-zinc-800 dark:text-zinc-100",
    "h4" => "text-3xl tracking-tight text-zinc-800 sm:text-3xl dark:text-zinc-100",
    "p" => "mt-6 text-base text-zinc-600 dark:text-zinc-400",
    "a" => "text-m font-medium text-teal-500"
  }
  defp add_tag_class({tag, attrs, ignored, meta}) do
    new_attrs = if class = @tag_to_class[tag], do: [{"class", class}], else: []
    {tag, attrs ++ new_attrs, ignored, meta}
  end

Then the following to my use NimblePublisher invocation:

  use NimblePublisher,
    # ...
    earmark_options: Post.earmark_options(),
    # ...

The postprocessor option gives you a hook which lets you work with the AST.

I also had to add this to my tailwind.config.js:

module.exports = {
  content: [
    // ...
    "../lib/path/to/post.ex",
    // ...
  ],

So it would pickup the new classes.

matthewsinclair

matthewsinclair OP

That’s a neat way to solve this (and more robust than my ropey attempt). Thanks!

adamu

adamu

I don’t know if it’s the best way, but I store the images one directory below the markdown and serve them with Plug.Static.

My markdown is saved in priv/posts and rendered on the /blog/:title route.
I made priv/posts/images to store the images, and then set up a new Plug.Static in the endpoint to serve them on the same /blog scope:

  plug Plug.Static,
    at: "/blog/",
    from: {:my_app, "priv/posts"},
    gzip: false,
    only: ["images"]

Then in your markdown:

![](images/lovely.jpg)

If we place the image in priv/posts/images/lovely.jpg, it should load.

You can also use an <img> tag directly in the markdown if you need to control the width/height:

<img src="images/lovely.jpg" width="100px" height="50px" />

It’s worth mentioning that unfortunately we can’t get the benefits of Phoenix verified routes or mix.digest for the images, because the markdown is injected as raw HTML and not rendered by Phoenix, so unable to get the route information (theoretically it might be possible to do it, because both the markdown and HEEX templates are parsed at compile-time, but I didn’t try it…). This means that we have to directly link to the image and won’t get warnings for invalid image paths and may end up with broken images (like this dashbit post at the time of writing).

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews