Style topics differently by category



  • Hi there,

    Is there any way to style topics differently based on the category they belong to? The current page name is appended to the <body> tag as a class, but I can't find a way for the CSS to know anything about a topic's parent category.

    I can solve the issue with a javscript hack by reading the category name from the breadcrumbs, but this seems ... terrible.

    Is there a less terrible way to expose category information to the topic template?


  • Admin

    You can do it with a plugin, listen for the hook filter:middleware.render and add the class you want to the bodyClass string if the user is on a topic page. Here is some code to get you going.

    // this goes in your plugin
    myPlugin.onPageRender = function (hookData, callback) {
      // this checks if we are on the topic page
      if (hookData.templateData.template.topic) {
        // add the class `category-<cid>` to bodyClass
        hookData.templateData.bodyClass += ' category-' + hookData.templateData.category.cid;
      }  
      callback(null, hookData);
    };
    

    Hope that helps.



  • fantastic! my codebase is much happier now


Log in to reply
 


Looks like your connection to NodeBB was lost, please wait while we try to reconnect.