Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

💬 How to apply rules like in v1 for v2? #122

Open
hbinduni opened this issue Dec 9, 2024 · 3 comments
Open

💬 How to apply rules like in v1 for v2? #122

hbinduni opened this issue Dec 9, 2024 · 3 comments

Comments

@hbinduni
Copy link

hbinduni commented Dec 9, 2024

i create rules for v1 like below:

converter := htmltomarkdown.NewConverter("", true, nil)

// Add a custom rule for the <img> tag
converter.AddRules(
htmltomarkdown.Rule{
	Filter: []string{"img"},
	Replacement: func(content string, node *goquery.Selection, options *htmltomarkdown.Options) *string {
		// Get attributes from the <img> tag
		src, _ := node.Attr("src")
		alt, _ := node.Attr("alt")
		title, _ := node.Attr("title")

		// Return a custom Markdown format
		result := fmt.Sprintf("![Custom Format | Alt: %s | Title: %s](%s)", alt, title, src)
		return &result
	},
},
)

how to apply rules for v2?
is that correct to apply rules like v1 using custom render in v2?
something like this:

conv := converter.NewConverter(
		converter.WithPlugins(
			base.NewBasePlugin(),
			commonmark.NewCommonmarkPlugin(),
		),
	)
	
conv.Register.RendererFor("img", converter.TagTypeInline, func(ctx converter.Context, w converter.Writer, node *html.Node) converter.RenderStatus {
		src := getAttribute(node, "src")
		alt := getAttribute(node, "alt")
		title := getAttribute(node, "title")

		// Custom Markdown for <img> tags
		w.WriteString(fmt.Sprintf("![Custom Format | Alt: %s | Title: %s](%s)", alt, title, src))
		return converter.RenderSuccess
	}, converter.PriorityEarly)

thank you

@hbinduni hbinduni changed the title How to apply rules like in v1 for v2? 💬 How to apply rules like in v1 for v2? Dec 9, 2024
@JohannesKaufmann
Copy link
Owner

  • There is an example for Register in examples/register/main.go

  • You can use the function dom.GetAttributeOr(node, "alt", "") from the "github.com/JohannesKaufmann/dom" package.

  • The Rule in V1 was quite limited. With V2 there is a lot more customisation possible. For most case the RendererFor is what you need.

  • If you want to package logic, you can optionally package it into a plugin. But registering it like you do right now is perfectly okay.

  • @hbinduni The logic above seems to be good 👍

@hbinduni
Copy link
Author

hbinduni commented Dec 9, 2024

Thank you for your help

@JohannesKaufmann
Copy link
Owner

No problem, happy to help!

Let me know if you have any other questions...

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants