You may be able to do that. But it would be a bit convoluted as you would need to first split the URL string and then render it as a class. I haven’t tried this myself, nor have I seen such a request before.
But it does sound kind of uneconomical. I mean slugs are supposed to be unique SEO wise. Also how much CSS do you plan on writing?
Why don’t you go for a simpler approach? Like assigning the class you need as a tag to your content pages and then render that tag as a class in your container. With this approach you will also be able to reuse that class whenever you need it.
Can you give a specific example? Your topic is asking for a “post/section slug”, but you reference single.html, as well as “…the-page-or-post-slug”, but on a section element, which is normally used for lists of different content (meaning a different rendering context in Hugo).
So let’s focus on one thing, explain what you are looking for with different templates and layouts, and we can go from there.
I have a folder called _default/ which has a single.html file into it. This single.html file has an HTML article tag which should have an assigned class corresponding to current viewed content slug.
So, If I create a file called my-first-post.md located into content/posts/ folder, could it be possible to retrieve the post slug my-first-post as a CSS class into the corresponding layouts/_default/single.html file?
I don’t know of a way to get just the slug, but we can get close, using {{ .URL }} or {{ .RelPermalink }}, and then processing the output using a function; I don’t know how to do that, so you can poke around in the docs or wait for someone that does know.
Hey, why are you doing this? As onedrawingperday mentioned, it is probably easier to define this in front matter, for the pages you need to style or reference differently. If you explain your use case, we might have an alternative solution.
Just tried {{ .Slug }} in my single.html template and it works for me (n.b. I always set slug in the frontmatter so if it is not set, ymmv, not sure). Nothing stopping you from sticking that in a class="" I would think, to allow per page specification. Creative use of it.
@rickcogley I was expecting something like that yeah (as WordPress, if you see what I mean) but in that case I have to instantiate a slug key in my front-matter in order to be used. So, could this case be a new feature? I mean, could it be possible to create a Pull Request in order to automatically use the filename as a slug value if the slug key in front-matter isn’t instantiated, when {{ .Slug }}?
@alexandros I was hoping something like @rickcogley’s solution. In some cases, it could be interesting to have a class in order to visually apply/modify HTML elements instead of creating an other layout…