stephen murdoch

How to add H2 tags to Trix editor

Trix Editor

Trix lacks H2 tags out the box, here's how to add them

Trix is a rich text editor from 37signals, aka Basecamp, which is built-in to ActionText, making it easier to add rich text content to Rails apps.

I'm using it here on this website. In fact I'm using it right now to type this post.

The toolbar at the top of the editor has a button for adding header tags. By default it spits out H1 tags, but I already add an H1 elsewhere in my markup, and would prefer if the button added an H2 tag instead.

I took a few wrong turns looking for the best way to do this, and in the end it was surprisingly simple. All I needed was the following javascript:

Trix.config.blockAttributes.heading1.tagName = "h2"

Tada. That was easy.  Now when I hit the heading button, it inserts an H2 tag into my document, rather than an H1, which suits my document outline more.

Where should I put the javascript?

You could put it in app/javascript/application.js, where you are probably already importing the trix editor into your rails app.

I actually moved the code that imports both trix and actiontext into a separate file named admin.js, which I only load when I'm creating or editing a post. This helps reduce the amount of javascript regular non-admin users have to download when they hit my site. 

My admin.js file looks like this:

import "trix"
import "@rails/actiontext"

Trix.config.blockAttributes.heading1.tagName = "h2"

That's about it for now.