Shortcode, readFile and javascript

Something strange is happening and I don’t understand why … :roll_eyes:

I created a javascript-file “test.js” with a few lines of code

console.log("1");
console.log("2");
console.log("3");

and a shortcode “jscript” to embed the file in the page. The shortcode is located in the file “jscript.html”

{{- $file := printf "%s%s%s" "content/" .Page.File.Dir (.Get "file") -}}
{{ readFile $file | safeHTML }}

and is called like this

{{< jscript file="test.js" >}}

The content of the javascript file is displayed within the page content as expected.

However, when I enclose the two lines of code in a “script” tags

<script type="text/javascript">
{{- $file := printf "%s%s%s" "content/" .Page.File.Dir (.Get "file") -}}
{{ readFile $file | safeHTML }}
</script>

the output of the readFile is changed to this:

<script type="text/javascript">"console.log(\"1\");\nconsole.log(\"2\");\nconsole.log(\"3\");"
</script>

If I use “div” or “pre” tags instead of “script”,

<pre>
{{- $file := printf "%s%s%s" "content/" .Page.File.Dir (.Get "file") -}}
{{ readFile $file | safeHTML }}
</pre>

everything looks as expected:

<pre>console.log("1");
console.log("2");
console.log("3");
</pre>

Does anyone have an idea what is happening and why?

I would avoid readfile, code defensively, and pass the content through the safeJS template function.

content/
├── posts/
│   └── post-1/
│       ├── index.md
│       └── test.js
└── _index.md

layouts/shortcodes/jscript.html

{{ with .Page.Resources.Get (.Get "file") }}
  <script type="text/javascript">
    {{ .Content | safeJS }}
  </script>
{{ end }}
2 Likes

Thanks,

I wasn’t aware safeHTML interferes wth the script tags as I saw javascript as a part of HTML.

What is the reason you’d avoid readFile? Performance? Error handling? or something else?

Good question. I thought that template functions in the os namespace did not work with content mounts, but I just tested them again and they work.

If you use os.ReadFile, you can avoid hardcoding the content directory.

The os.ReadFile function attempts to resolve the path relative to the root of your project directory. If a matching file is not found, **it will attempt to resolve the path relative to thecontentDir]. A leading path separator (/ ) is optional.

2 Likes

Good point and I admit your suggestion looks more elegant :smiley:

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