What are the uses of $ in Hugo

What are the use cases and the contexts in which $ can be used in Hugo and where can I read more about the use of the $ operator?

1 Like

Use $. to Access the Global Context.

1 Like

Many thanks for the answer. I am new to go, go templates and hugo.

This is a follow-up question on Pass Global Context to Partial | Capture Global Context:

I want to know if this is valid;

  1. {{ $var := $ }} to assign global context to a variable
  2. {{ partial "page/head" $ }} to pass global context to a template

If the above is not valid what is the way to achieve it?

Now I think you may be looking for .Scratch

It’s always a guessing game if I have no idea about what you’re trying to achieve.

Maybe this can help you further. Again, I’m assuming you’re looking for something like .Scratch.

Problem I am having is the I loose the outer context when withing a with statement. I want to (1) recover the outer context or (2) use global context passed to a template when that would work.

1 Like

Right, everything is easier with an example. You could define variables, outside the with block, and use them afterwards, like this:

{{ $outerVar := .Params.OrWhatever }}

{{ with .Params.something }}
  {{ $outerVar }}
{{ end }}

And sorry, I didn’t understand the second one.

It’s in the docs. https://gohugo.io/templates/introduction/#1-define-a-variable-independent-of-context

I strongly recommend reading all of the docs, and then trying to actually create a Hugo project. Then when you have a specific question, you can share your code and point to what part of your code is confusing or does not work.

Also useful to read Requesting Help and Recommended Reading Reference

1 Like

I struggled myself with this several years ago. This might help: https://regisphilibert.com/blog/2018/02/hugo-the-scope-the-context-and-the-dot/

3 Likes

@regis I already gave him a link to you brilliant post in another of his (numerous) threads

I see. Thanks.