點燈坊

失くすものさえない今が強くなるチャンスよ

Using with to Change the Context

Sam Xiao's Avatar 2022-01-11

We can use with to change the context and . as the context variable.

Version

Hugo 0.91

Page

with000

Display title by page variable.

Page Variable

content/_index.md

---
title: My Blog
---
  • title : default page variable defined by Hugo

with

layouts/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="alpine.js" defer></script>
    <link rel="stylesheet" href="output.css" />
  </head>
  <body>
    {{ with .Title }}
    <h1 class="text-4xl font-bold">{{ . }}</h1>
    {{ end }}
  </body>
</html>

Line 10

{{ with .Title }}
<h1 class="text-4xl font-bold">{{ . }}</h1>
{{ end }}
  • with : change the context to $.Title
  • . : context variable to access the current context

Conclusion

  • If we have to access a variable many times, we can use with to change the context first, and then use . to access it