I’d like to add hashtags to specific terms in my article titles.
Example: Buy apples from New York --> Buy #apples today from #NewYork
Example2: New shipment of oranges from Florida --> New #shipment of #oranges from #Florida.
I’ve tried to do this as follows:
{{range .Pages}}
{{if in .Title "apples"}}
{{replace .Title "apples" "#apples"}}
{{else if in .Title "New York"}}
{{replace .Title "New York" "#NewYork"}}
...
{{end}}
{{end}}
The problem with this approach is that it won’t replace multiple words in a title and the amount of conditionals needed is huge. I have a list of about 20 terms that need a hashtag. Any ideas how I can improve upon this?
The only better approach I can think of would be to use dict
with the terms you need to have a hashtag and then create a variable with scratch
that is for these terms in your titles.
See this topic to get an idea of how you may be able to pull this off.
1 Like
With the help of your code I got it to work. Thank you!
For someone else stumbling across this thread, it would be nice if you can show your final solution. Thanks
1 Like
Sure thing.
{{$hashtags := (dict "Apple" "#Apple" "New York" "#NewYork")}}
{{range .Pages}}
{{$.Scratch.Set "hashtagTitle" .Title}}
{{range $k, $v := $hashtags}}
{{$.Scratch.Set "hashtagTitle" (replace ($.Scratch.Get "hashtagTitle") $k $v)}}
{{end}}
{{$.Scratch.Get "hashtagTitle"}}
{{end}}
1 Like