runhide
February 26, 2019, 1:09am
1
With the following code, which works, I count the number of products, manufacturers and plants
.
{{$.Scratch.Set "productCounter" 0}}
{{range .Pages}}
{{$.Scratch.Add "productCounter" 1}}
{{$.Scratch.Add "manufacturerCounter" (.Params.manufacturers)}}
{{$.Scratch.Add "plantCounter" (slice .Params.plant)}}
{{end}}
{{$.Scratch.Get "productCounter"}}
{{$.Scratch.Set "manufacturerCounter" ($.Scratch.Get "manufacturerCounter" | uniq)}}
{{len ($.Scratch.Get "manufacturerCounter")}}
{{$.Scratch.Set "plantCounter" ($.Scratch.Get "plantCounter" | uniq)}}
{{len ($.Scratch.Get "plantCounter")}}
This code is quite repetitive, so I’m asking for refactoring help. I was thinking of something like this:
{{$.Scratch.Add "counter" (dict "products" 1 "manufacturers" .Params.manufacturers "plants" (slice .Params.plant))}}
But I couldn’t get it to work. I need to be able to access each parameter: products, manufacturers and plants
.
Do you need to use .Scratch
?
Since Hugo 0.48 we’ve been able to overwrite variables. This wouldn’t solve everything but would make the code a little more readable.
runhide
February 26, 2019, 12:51pm
3
That’s interesting. I must have missed that functionality. I’ve played around with this and refactored productCounter
to use a variable instead of .Scratch
, but I can’t figure out how to do the same with manufacturerCounter
and plantCounter
as I need to count only unique values.
{{$productCounter := 0}}
{{range .Pages}}
{{$productCounter = add $productCounter 1}}
{{$.Scratch.Add "manufacturerCounter" (.Params.manufacturers)}}
{{$.Scratch.Add "plantCounter" (slice .Params.plant)}}
{{end}}
{{$productCounter}}
{{$.Scratch.Set "manufacturerCounter" ($.Scratch.Get "manufacturerCounter" | uniq)}}
{{len ($.Scratch.Get "manufacturerCounter")}}
{{$.Scratch.Set "plantCounter" ($.Scratch.Get "plantCounter" | uniq)}}
{{len ($.Scratch.Get "plantCounter")}}
Can you assist?
runhide
February 26, 2019, 1:14pm
4
Just managed to figure this out. This is what I’ve got. If you have any suggestions on how to improve this, let me know.
{{$productCounter := 0}}
{{$manufacturerCounter := slice}}
{{$plantCounter := slice}}
{{range .Pages}}
{{$productCounter = add $productCounter 1}}
{{$manufacturerCounter = append $manufacturerCounter .Params.manufacturers}}
{{$plantCounter = append $plantCounter (slice .Params.plant)}}
{{end}}
{{$productCounter}}
{{len ($manufacturerCounter | uniq)}}
{{len ($plantCounter | uniq)}}
1 Like