Pipes ExecuteAsTemplate

I’m want some specific CSS included in a page if a shortcode is used, and I want that CSS to be dynamic based on some Params set in the front matter.

In layouts/partials/head.html I have the following:

{{- if (.Page.HasShortcode "myShortcode") -}}
    {{- $finalCSSPath := print .Page.RelPermalink "css/myShortcode.css" }}
    {{- $shortcodeCSS := resources.Get "templates/myShortcode.css" | resources.ExecuteAsTemplate $finalCSSPath . }}
  <link rel="stylesheet" type="text/css" href="{{ $shortcodeCSS.RelPermalink }}">
{{- end -}}

which generates the param based css and outputs it to css/myShortcode.css relative to the page that included the shortcode.

That was working fine, but I just added a second page with the same shortcode, and now both pages always get the same generated CSS from the template, so it’s not specific for each page. Also, when I look at how many times the "templates/myShortcode.css" file is executed, it’s only run once.

     cumulative       average       maximum         
       duration      duration      duration  count  template
     ----------      --------      --------  -----  --------
    17.174424ms    8.587212ms    9.323163ms      2  _default/single.html
    11.059626ms    3.686542ms     5.52871ms      3  partials/head.html
     3.050797ms    3.050797ms    3.050797ms      1  templates/compare.css

So the head.html partial is being run 3 times (correct: one list page, two pages with the shortcode, but the template is only being called once.

Does the resources.ExecuteAsTemplate cache or am I not understanding how it’s supposed to work? Wanted to check if there’s an known/obvious reason for this before I try to recreate in a simple test repo.

Using Hugo Static Site Generator v0.69.0/extended darwin/amd64 BuildDate: unknown

It does, but only based on the first argument (the path).

In my example, the path is different every time as it’s relative to the current page, yet I’m seeing the same file output in both places.

{{- $shortcodeCSS := resources.Get "templates/myShortcode.css" | resources.ExecuteAsTemplate $finalCSSPath . }}

I’ll try to recreate in a simple repo.

Thanks @bep, it was caching.

The code I included here was simplified to explain the problem, and I had removed a resource.Concat call. So the the .ExecuteAsTemplate was in fact using the same path for every call.

Added a temp variable to change the path each time through, and working perfectly.

1 Like

Good, I had been a little bit surprised if that bug had not been caught by me (and others) before …

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.