sirthias / pegdown

A pure-Java Markdown processor based on a parboiled PEG parser supporting a number of extensions
http://pegdown.org
Apache License 2.0
1.29k stars 218 forks source link

add css class to table #158

Open stevenemrick opened 9 years ago

stevenemrick commented 9 years ago

Is there a way to do this? I'm using the data tables plugin which can be activated on a code snippet:

('table.my-table-class').dataTable( {
         "paging":   false,
         "ordering": true,
         "searching": false,
         "responsive":true
          } );

So the use case is that I need to identify certain tables (not all tables) that can be post-processed using this plugin. Thanks for your consideration.

vsch commented 8 years ago

You can define your own HTML renderer and override the visit(TableNode) function.

import org.pegdown.LinkRenderer;
import org.pegdown.ToHtmlSerializer;
import org.pegdown.VerbatimSerializer;
import org.pegdown.ast.TableNode;
import org.pegdown.plugins.ToHtmlSerializerPlugin;

import java.util.List;
import java.util.Map;

public class MyToHtmlSerializer extends ToHtmlSerializer {
    public MyToHtmlSerializer(LinkRenderer linkRenderer) {
        super(linkRenderer);
    }

    public MyToHtmlSerializer(LinkRenderer linkRenderer, List<ToHtmlSerializerPlugin> plugins) {
        super(linkRenderer, plugins);
    }

    public MyToHtmlSerializer(LinkRenderer linkRenderer, Map<String, VerbatimSerializer> verbatimSerializers) {
        super(linkRenderer, verbatimSerializers);
    }

    public MyToHtmlSerializer(LinkRenderer linkRenderer, Map<String, VerbatimSerializer> verbatimSerializers, List<ToHtmlSerializerPlugin> plugins) {
        super(linkRenderer, verbatimSerializers, plugins);
    }

    public void visit(TableNode node) {
        currentTableNode = node;
        printIndentedTag(node, "table class=\"my-table-class\"");
        currentTableNode = null;
    }
}

then use your class instead of the one provided by pegdown. You can also override the link renderer if you want to customize link generation. There are many variations of the functions for toHTML() that take various parameters. You can use any of them to suit your needs. This is only a simple example of how you would use the custom HTML serializer:

    String markdownToHtml(String markdown) {
        PegDownProcessor processor = new PegDownProcessor();
        RootNode rootNode = processor.parseMarkdown(markdown.toCharArray());
        ToHtmlSerializer htmlSerializer = new MyToHtmlSerializer(new LinkRenderer()); 
        String html = htmlSerializer.toHtml(rootNode);
        return html;
    }
isapir commented 7 years ago

But that will affect all tables, no?

It'd be good to allow adding css classes so that different tables can be styled differently.

stevenemrick commented 7 years ago

yes exactly. I want a simple syntax to add css classes to tables, or even other block elements.