-
I need to rewrite links to local images because of dynamic access rules, how can I do that? I looked at the AST and extensions but it seems quite complicated and looks like it's mostly about adding support for custom syntax rather than being able to alter the source for specific elements. Is there an easy way to do this or do i have to use regular expressions and replace the links before passing the text to goldmark itself? I'd like to do it via extension to have the guarantee that i am altering the actual image link and not just a text that matches the regex but won't be rendered as such by goldmark(especially if there is image wrapped by a link). |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
still active issue for me... |
Beta Was this translation helpful? Give feedback.
-
You should be able to do this by adding an ASTTransformer to your parser. tr := &imageLinkRewriter{}
md := goldmark.New(
goldmark.WithParserOptions(
parser.WithASTTransformers(util.Prioritized(tr, 100)),
),
) Where For example, type imageLinkRewriter struct{}
func (t *imageLinkRewriter) Transform(doc *ast.Document, reader text.Reader, pctx parser.Context) {
ast.Walk(doc, func(node ast.Node, enter bool) (ast.WalkStatus, error) {
if !enter {
return ast.WalkContinue, nil
}
link, ok := node.(*ast.Link)
if !ok {
// Not a link. Leave it unchanged.
return ast.WalkContinue, nil
}
// modify the link here
// Don't descend into the link children.
return ast.WalkSkipChildren, nil
})
} Link holds information about the link. It embeds baseLink, so that gives it the following fields:
If you inspect and modify u, err := url.Parse(string(link.Destination))
if err == nil && u.Host == "" && !path.IsAbs(u.Path) {
// The URL is a relative path.
link.Destination = whatever(u)
} |
Beta Was this translation helpful? Give feedback.
-
It works. But is there a way to pass proper context to it from md.Convert() ? I am looking at passing parser.NewContext() via Convert's parser.ParseOption but that is some custom md context, not proper context. So far I am using this and it seems to be working:
and
|
Beta Was this translation helpful? Give feedback.
You should be able to do this by adding an ASTTransformer to your parser.
Start with something like the following:
Where
imageLinkRewriter
is your transformer.It should satisfy the ASTTransformer interface.
That lets you do anything to the document,
but typical usage involves traversing the document with ast.Walk.
For example,