Cannot strip file extension from filename variable

Hello there

I am trying to list markdown files contained in a directory with the extension stripped. What follows is a minimized example of what I am trying to do.

The directory layout:

Caddyfile
index.html
posts
 |---test1.md
 |---test2.md

The contents of the Caddyfile:

localhost
errors
templates
ext .html .md

The contents of index.html

<h1>List of posts:</h1>
<ul>
{{range $f := .Files "/posts"}}
  <li>{{.StripExt $f}}</li>
{{end}}
</ul>

Caddy’s templating is unable to use the .StripExt method on the $f variable containing the filename. This results in an 500 internal server error when accessing the page.

Resulting error in the logfile:

executing "/" at <.StripExt>: can't evaluate field StripExt in type string

If anyone could help, it would be much appreciated.

Inside a loop, the context scope changes. See template package - text/template - pkg.go.dev

You need to reference the global scope with $ like $.StripExt:

When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

Thanks for the information. That fixed my issue.

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