How to generate partial & static asset links based from a front matter variable?

I have code that works (!) but am looking for someone with more experience templating for any advice on something more elegant.

I’m looking to generate links to a partial and static asset files (CSS & JS) that are based on a front matter variable - in my case it’s a number.

I set each piece of content to have a number (day = "01" for example), and it grabs CSS & JS files per content and pulls them in.

<link rel="stylesheet" href="{{ (delimit (slice "css/day" .Params.Day ".css") "") | absURL }}" type="text/css" />

And then do the same for a partial call:
{{ partial (string (delimit (slice "demo/day" .Params.Day ".html") "")) . }}

This was based on my understanding (and trial and error) from the documentation:

  • Slice seems to create spaces between things squashed together, so it needed delimit with an empty string to remove them
  • Use absURL to ensure file path is correct, as site is sitting in a sub-folder
  • Need to make it a string for the partial call to work

Is this the best way to achieve this, or is there a better / more efficient solution? Something feels off/unnecessary with what I’ve done. Many thanks.

I can’t think of any better way to do what you’re trying to do.

There’s separating them into different sections, then hard-coding the CSS/JS into the templates for each section - you can use the {{ block }}/{{ define }} method to replace the CSS/JS for each section. That would theoretically be easier, unless you don’t want the pages separated by section.

There are some things that Hugo isn’t necessarily built to do, so sometimes weird workarounds like yours end up being made, to do the things we want to in our templates.

1 Like

Thank you. That’s good to know!

I have the CSS/JS tags in partials at the moment, pulled in at the right area using the block/define method. The template for the single page basically goes 1. CSS partial, 2. HTML partial, 3. JS partial.

One of the things that trips me up is there’s a few different ways to achieve similar things, so I’m glad that the code is basically alright for this. Thanks!