pragdave / earmark

Markdown parser for Elixir
Other
860 stars 135 forks source link

Custom resolver for links and images #247

Closed crertel closed 5 years ago

crertel commented 5 years ago

When using Earmark for blog posts or images, I've resorted to crawling the generated HTML with Floki and doing weird in-place transforms and re-rendering the HTML.

If I had a way of consuming the referenced URLs for links and images, in some sort of middleware or similar, I wouldn't have had to do this.

This biggest application for this would be implementing a wiki--e.g., for allowing users to use friendlier names for resources like [this](#wiki_article_for_this) instead of having to know the URLs ahead of time.

Thoughts?

RobertDober commented 5 years ago

If I understand correctly exposing an AST as foreseen in #145 should do the trick.

Hopefully I will get to it in the nearer future.

If 145 cuts it, please close this issue, if not please explain what else would be a good solution for you?

RobertDober commented 5 years ago

or would you just want [this](#whatever) to create <a href="#whatever">this</a> :question:

crertel commented 5 years ago

I'd ideally like to be able to do this without touching an AST--that being the solution I've already got in place via Floki.

It feels like there should be an "easy" way of registering a module that is called with image and link resources paths (typically just URLs, but again that need not be the case, see the hypothetical [wiki](#wiki) syntax.

crertel commented 5 years ago

Like, a hacky version demonstrating this would just be to modify the link and image helpers to interpolate from a helper passed the link string instead of directly interpolating the link address itself.

Basically:

 ~s[<img src="#{path}" alt="#{alt}"/>]

...could become...

 ~s[<img src="#{resolve_path(path)}" alt="#{alt}"/>]

With resolve_path/1 looking like:

def resolve_path( path ) when is_binary(path) do
    resource_handler = Application.fetch_env!(:earmark, :resource_lookup)
    resource_handler.lookup(path)
end

Obviously just a super quick hack, but see what I mean?

RobertDober commented 5 years ago

Actually I am confused, how will you get the :resource_lookup into Earmark's environment?

crertel commented 5 years ago

Oh I have no idea!

In some other language (say, C or JS or whatever) there'd be a function where you could register a handler. I don't know the Earmark codebase well enough to sketch out how that might be implemented.

RobertDober commented 5 years ago

To my knowledge it is impossible from a client library, but my knowledge is limited, I need to investigate.

RobertDober commented 5 years ago

As discussed in many related issues this shall be covered by an exposed AST as sketched in #145