11ty / eleventy-plugin-syntaxhighlight

A pack of Eleventy plugins for syntax highlighting in Markdown, Liquid, and Nunjucks templates.
https://www.11ty.dev/docs/plugins/syntaxhighlight/
MIT License
130 stars 32 forks source link

Allow custom attributes to be applied to pre and code tags #48

Closed andria-dev closed 3 years ago

andria-dev commented 3 years ago

Fixes #22

I created a function, getAttributes(attributes), that takes either a string or an object of strings or numbers and outputs a string of HTML attributes. This function is then used to allow the use of the following options: preAttributes and codeAttributes. Usage is as follows:

const syntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight");

module.exports = function(eleventyConfig) {
  eleventyConfig.addPlugin(syntaxHighlight, {
    preAttributes: { tabindex: 0 }
  });
};

This will add tabindex="0" to the <pre> tag — allowing code blocks with scrollbars to be keyboard accessible — like so:

<pre class="language-js" tabindex="0"><!-- etcetera --></pre>
zachleat commented 3 years ago

Going to merge this but I wonder if we should also change tabindex="0" to be added by default? Maybe in the next major version

I’ll probably also remove the string support as I think the object literal support is probably sufficient (if you disagree please chime in!)

zachleat commented 3 years ago

Filed the tabindex question at #49

chriskirknielsen commented 3 years ago

This is fantastic! I added PR #50 to enable dynamic attributes to be generated based on context data — this will for example allow the language to be provided directly as an attribute (see #22 use-case, solved with example below). I hope this isn't already available with this PR as I couldn't get it to work, but please let me know if I'm wrong.

eleventyConfig.addPlugin(pluginSyntaxHighlight, {
    preAttributes: {
        'data-lang': function (context) { return context.language.toUpperCase(); }
    }
});