1- function attributeEntryToString ( [ key , value ] ) {
1+ function attributeEntryToString ( attribute , context ) {
2+ let [ key , value ] = attribute ;
3+
4+ if ( typeof value === "function" ) { // Callback must return a string or a number
5+ value = value ( context ) ; // Run the provided callback and store the result
6+ }
7+
28 if ( typeof value !== "string" && typeof value !== "number" )
39 throw new Error (
4- `Attribute "${ key } " must have a value of type string or number not "${ typeof value } ".`
10+ `Attribute "${ key } " must have, or evaluate to, a value of type string or number, not "${ typeof value } ".`
511 ) ;
612
713 return `${ key } ="${ value } "` ;
@@ -15,21 +21,23 @@ function attributeEntryToString([key, value]) {
1521 * ```js
1622 getAttributes({
1723 tabindex: 0,
18- 'data-language': 'JavaScript' ,
24+ 'data-language': function (context) { return context.language; } ,
1925 'data-otherStuff': 'value'
2026 }) // => ' tabindex="0" data-language="JavaScript" data-otherStuff="value"'
2127 ```
2228 *
2329 * @param {{[s: string]: string | number} } attributes An object with key-value pairs that represent attributes.
30+ * @param {object } context An object with the current context.
31+ * @param {string } context.content The code to parse and highlight.
32+ * @param {string } context.language The language for the current instance.
33+ * @param {object } context.options The options passed to the syntax highlighter.
2434 * @returns {string } A string containing the above HTML attributes preceded by a single space.
2535 */
26- function getAttributes ( attributes ) {
36+ function getAttributes ( attributes , context ) {
2737 if ( ! attributes ) {
2838 return "" ;
2939 } else if ( typeof attributes === "object" ) {
30- const formattedAttributes = Object . entries ( attributes ) . map (
31- attributeEntryToString
32- ) ;
40+ const formattedAttributes = Object . entries ( attributes ) . map ( entry => attributeEntryToString ( entry , context ) ) ;
3341 return formattedAttributes . length ? ` ${ formattedAttributes . join ( " " ) } ` : "" ;
3442 } else if ( typeof attributes === "string" ) {
3543 throw new Error ( "Syntax highlighter plugin custom attributes on <pre> and <code> must be an object. Received: " + JSON . stringify ( attributes ) ) ;
0 commit comments