點燈坊

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

Using Hugo Variables with Alpine

Sam Xiao's Avatar 2022-02-15

Not only using Hugo’s variables with Go template language, but also Alpine’s directive.

Version

Alpine 3.9
Hugo 0.92

Alpine

alpine000

Use Alpine’s x-for to simply loop n number of time, but the number is defined by Hugo’s site variable, not Alpine’s variable.

Layout

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" />
    {{ $number := 3 }}
  </head>
  <body x-data>
    <ul>
      <template x-for="x in {{ $number }}">
        <li x-text="x" />
      </template>
    </ul>
  </body>
</html>

Line 8

{{ $number := 3 }}

Define $number template variable by Go template language.

Line 10

<body x-data>
  <ul>
    <template x-for="x in {{ $number }}">
      <li x-text="x" />
    </template>
  </ul>
</body>

Alpine’s x-for is using Hugo’s $number.

Conclusion

  • We can also use Hugo’s site variables and page variables with Alpine.