HUGO

How can you use a partial HTML file inside a template as a function?

Hello, and sorry if I’m bothering you. I tried to read other threads on this forum and on stackoverflow, but I didn’t manage to find a solution for this problem.

What I’d like to do is to pick a phone number in a string format, like this:

(+39) 347 1234567

And use it to create a phone link as this:

<a href="tel:+393471234567">(+39) 347 1234567</a>

The problem is that I need to do this job multiple times. Instead of having to copy & paste this code many times I’d rather prefer to create a sort of “function” that I could call anywhere in my template.
As I tried to build this sort of “function”, I have create a partial file named phone.html that contains this very basic code:

{{ $link := . }}
{{ $link := replace $link "(" "" }}
{{ $link := replace $link ")" "" }}
{{ $link := replace $link " " "" }}
<a href="tel:{{ $link }}">{{ . }}</a>

The problem is this: when I call this partial from my main block in index.html with this code:

<p>
  Call our number 
  {{ partials "phone.html" (dict "context" .Site.Params.phone) -}}
</p>

On my website I read this:

Call our number {0xc000183680 0xc0006fd400} 

Could you explain me what am I doing wrong, please ?
I’m using Hugo v0.82.0-extended.

Inside your partial, the “dot” will be the whole dict.

See the difference for yourself:

<!-- partial -->
{{ . }}
{{ .context }}

1) Use := to declare a variable, setting the initial value. Use = to change the value.

2) When calling a partial use the partial statement, not partials.

3) As @pointyfar described, the only thing you need to pass to your partial is the phone number.

{{ partial "phone.html" .Site.Params.phone }}

4) When you fix #1, #2, and #3, the result will still be wrong because the plus sign within the href attribute will be encoded; this is incorrect. You’ll need to use the safeHTMLAttr function.

This is the cleanest partial that I could come up with:

{{ $href := printf "tel:%s" (replaceRE `[() ]` `` .) }}
<a {{ printf "href=%q" $href | safeHTMLAttr }}>{{ . }}</a>

For someone new to Hugo that might be a bit daunting. See if you can figure it out.

https://gohugo.io/functions/printf/
https://gohugo.io/functions/replacere/
https://gohugo.io/functions/safehtmlattr/

Thank you very much for showing me where I went wrong, and for having shown me how I can write better code with Hugo.

Whoops, you are right. Thank you very much for letting me know.

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