I’m a newbie and just starting out with Hugo and I’m trying to customize a theme.
I want to use the same partial in the index.html multiple times but with different text that’s stored in data files. I understand how to iterate through all the data files and display all resulting partials at one go, but I can’t figure out how to display one partial with the input from one specific data file at a time … How can I tell the partial to just pull the data from one specific file?
Here’s what I have so far. This displays all partials instead of one at a time.
--> layouts: index.html
{{ partial "colorlines.html" . }} <-- how can I tell here which yaml data file to use in partial?
--> partial: colorlines.html
{{ range .Site.Data.colorlines }}
<section class="colorline background-c1">
<div class="container">
<div class="col-md-4 col-sm-12">
<h2>{{ .name }}</h2>
</div>
<div class="col-md-8 col-sm-12">
<div class="colorline-text">
<p>{{ .description }}</p>
</div>
</div>
</div>
</section>
{{ end }}
--> data: c1.yaml , c2.yaml etc.
name: "myname"
description: "my description"
So I technically want to do something like this in index.html:
{{ partial "colorlines.html" . use data from c1}}
... some other partials
{{ partial "colorlines.html" . use data from c2}}
I’m sure this is fairly easy and I searched the docs and forums for answers but I still don’t understand how to do this …
The partial template function allows you to pass the name of the partial and a context (a.k.a. the .) to access data within the template.
It’s actually possible to modify the last parameter. Your case can pass a dictionary that contains the context (for the case you need it) and the name of the data file. Alternatively, you could use the data file directly:
But I’m not sure if I understand how your first example works… if I pass the name of the data file it just prints out that string, not the data inside the data file. Like this:
This just puts the string “c1” into the {{.name}} inside the partial and so on the site it prints “c1”. From your explanation I understood that it should somehow pull the data from the c1.yaml file. Or is this how you meant it?
Thanks, yes I had tried something (kinda) like that in the partial but I have still difficulties with the syntax. But you’re right, the second example is a bit cleaner anyway.