Is it possible to set Redactor button to wrap my code snippets inside two tags?


This is what I have so right now.

formattingAdd: [
        tag: 'code',
        title: 'Code Inline'
        tag: 'pre',
        title: 'Code Well'
        tag: 'mark',
        title: 'Marked'

But some scripts and Bootstrap wants it wrapped in both of the tags.

2 Answers 2


If it were me, I'd try to keep as much formatting cruft out of a wysiwyg as possible, it cleans things up down the road and keeps your content as structured as possible. If you ever change frameworks or anything else, that extra cruft can come back to haunt you because it's all stored in the database.

A better way is handle this with a couple Matrix blocks. Set one up for text, and then another one for code snippets. Then in your template when you want to spit out a code snippet, you just wrap it using whatever extra bits you need like:

{% for block in entry.myMatrixField %}

{% if block.type == "text" %}
    {# handle text #}
    {{ block.entryText }}

{% elseif block.type == "code" %}

    <div class="code-snippet">
    <pre><code>{{ block.codeBlock }}</code></pre>

{% endif %}

{% endfor %}

The upside here is that it's all built-in, you don't have to modify any redactor defaults to make this work. But the bigger upside is if let's say you're building a library of code snippets, it'd be super easy to query the Matrix fields and get just those snippets you want.

You could even completely reformat the page and just show the code snippets, since you have them already broken out.

IMO that's what makes Craft so powerful, it's easy to use more structured data unlike other solutions *cough* like WordPress *cough* that put everything in one "field."

  • Hi and thanks for your answer. I currently have it set up with Matrix fields as you described. Sometimes having too many matrix blocks is bit daunting and takes longer to write. Since I'll be showing a bunch of code snippets I wanted to try and see if I can do it inline. I guess the only other option for me configure the highlighting JS to work without it being nested.
    – julzmon
    Commented Jan 4, 2015 at 2:43
  • 1
    FYI <pre> and <code> tags are not "formatting cruft" -- they are semantic tags which give meaning to the content. The style of them is determined by your CSS, and whether or not they are added in a wysiwyg editor has no bearing on the structure of your content.
    – Jordan Lev
    Commented Apr 19, 2017 at 6:03

I don't have the code handy, but a simple workaround might be to setup Redactor to use just one of the tags (either <pre> or <code>) and then replace these tags on the fly within your Twig templates.

Replace <pre> with <pre><code> and </pre> with </code></pre>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.