The above is a code snippet to print data from a Json file used in a shortcode. However, what I want to do is pass a file name in my template or md file so that I can read different files with the same code.
Include a link to the source code repository of your project, because we really need the context of seeing your templates and partials to be able to help you. It is trivial to do a quick git clone on your repo, then run hugo server in your project, to help you out. On the other hand, recreating your code from screenshots, or sort of guessing at it, is not.
If you can’t share your repository for whatever reason, consider creating a dummy repo that you can share, which reproduces the problem you’re experiencing.
`[quote=“yaheya, post:5, topic:39289, full:true”]
Here is a shortcode I wrote it works perfectly. Except it is static I want to inject the filename as a variable -
Market Summary
{{ range .Site.Data.stocks }}
{{end}}
Index
Value
Change
Percentage
{{.name}}
{{lang.NumFmt 2 .value}}
{{lang.NumFmt 2 .change}}
{{lang.NumFmt 2 .percentage}}
[/quote]
`Preformatted text``Here is a shortcode I wrote it works perfectly. Except it is static I want to inject the filename as a variable -
<h3>Market Summary</h3>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">Index</th>
<th scope="col">Value</th>
<th scope="col">Change</th>
<th scope="col">Percentage</th>
</tr>
</thead>
<tbody>
{{ $filename := .Params.myvar }}
{{ range index .Site.Data $filename }}
<tr>
<td>{{.name}}</td>
<td>{{lang.NumFmt 2 .value}}</td>
<td>{{lang.NumFmt 2 .change}}</td>
<td>{{lang.NumFmt 2 .percentage}}</td>
</tr>
{{end}}
</tbody>
</table>
myvar has the value "stocks" that comes from a front matter variable. I get the following error -
can’t evaluate field myvar in type interface {}
The goal is each md file will have a different filename so this routine will work for all pages.
<h3>Market Summary</h3>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">Index</th>
<th scope="col">Value</th>
<th scope="col">Change</th>
<th scope="col">Percentage</th>
</tr>
</thead>
<tbody>
{{ $filename := .Get "file" }}
{{ range index .Site.Data $filename }}
<tr>
<td>{{.name}}</td>
<td>{{lang.NumFmt 2 .value}}</td>
<td>{{lang.NumFmt 2 .change}}</td>
<td>{{lang.NumFmt 2 .percentage}}</td>
</tr>
{{end}}
</tbody>
</table>
I call the shortcode routine like so -
{{< stocks file="stocks" >}}
Each day I will have a different JSON file for the Stock Summary.
Thanks a lot!!