URL encoding within CSS style tags

Given the following template:

<style type="text/css">
  @import "{{ "css/demo.css" | relURL }}";
  @import "{{ "css/demo.css" | absURL }}";
</style>

I would expect the rendered template to look like this:

<style type="text/css">
  @import "/site/css/demo.css";
  @import "http://localhost:1313/site/css/demo.css";
</style>

However, Hugo is rendering the following:

<style type="text/css">
  @import "\2fsite\2f css\2f demo.css";
  @import "http\3a\2f\2flocalhost\3a 1313\2fsite\2f css\2f demo.css";
</style>

Interestingly enough, it works on all the browsers I tried (Chrome, FF, IE). If I move the lines outside of the “style” block, Hugo renders the content as I would expect. There’s some kind of CSS black magic going on.

Is this a bug or a “feature”? It makes visually verifying the rendered code extremely difficult. I’m using the latest from the master branch. I’m happy to create an issue on Github is this is a bug. Thanks

It’s a feature of the go templates. You need to tell the template that the value you are providing is actually already in it’s final format. I think you can do this with {{ "css/demo.css" | relURL | html }}

To explain it further why this is a feature. Go templates are context aware. They know that you are using that variable inside of a CSS block and that it should be escaped there since the go template doesn’t know that it’s safe to include it unescaped. Since you are controlling the value of that variable and you know it is safe you simply need to tell it that. I believe | html will work though it may be | safeHTML.

1 Like

Interesting. html and safeHTML doesn’t solve the problem, but the following does:

@import url("{{ "css/demo.css" | relURL }}");

Go templates needed the url() context. Thanks for pointing me in the right direction, Steve.

2 Likes