Sofia Johansson
Sofia Johansson

Reputation: 71

How do I include liquid/global variables defined using Jekyll in a Javascript file?

Currently I'm using Jekyll to build a website, with markdown and html files. If I want to use for example variables defined in the '_data' folder in html/md I can simply use {% for item in site.data.XX %}. My question is, what is the correct syntax when reaching Jekyll variables (e.g. site) in Javascript?

I am using frontmatter in my JS file. Should I include something there or do an import?

I tried:

But I just get the errors "Site is not defined" or "Uncaught SyntaxError: Invalid or unexpected token".

Upvotes: 3

Views: 1946

Answers (3)

ashmaroli
ashmaroli

Reputation: 5444

Jekyll is a static-site-generator that essentially runs just once. The only time it runs continuously is when you invoke either of the following commands: jekyll serve or jekyll build --watch.

On the other hand, JavaScript scripts are meant to be run on each request for a given page. Unless there's a server running with Jekyll, your scripts won't be able to use the so-called global variables.

However, that said, you can still use Jekyll variables to generate a static JS script. For example, consider the following contents:

./_data/navigation.yml

- label: Home
  url: "/"
- label: About Us
  url: "/about/"

./_includes/script-template.html

<script>
  {% for entry in site.data.navigation %}
    console.log('{{ entry.label }}');
  {% endfor %}
</script>

./test.html

---
---
<body>
  {% include script-template.html %}
</body>

If you were to build the site containing above files, the generated html file ./_site/test.html will look like the following:

<body>
  <script>

    console.log('Home');
    console.log('About Us');

  </script>
</body>

Upvotes: 1

Sofia Johansson
Sofia Johansson

Reputation: 71

I just found the problem (you solved it previously David): Jekyll: liquid tag inside javascript

It seems like it prints out correctly (without syntax errors) when adding:

console.log({{ site.collections | jsonify }})

Upvotes: 1

David Jacquel
David Jacquel

Reputation: 52789

Any file with a front-matter will be processed by jekyll...

eg : anyfile-with-front-matter.js

---
title: my js file
---
console.log({{page.title}});
console.log({{site.description}});

..., except if it is "ignored".

By default :

  • any underscored folder is ignored (eg: _myfolder)
  • node_modules, vendor/bundle/, vendor/cache/, vendor/gems/ and vendor/ruby/ folders are ignored by default configuration

To make contained files available to process, you can add containing folders to include array in your _config.yml.

include:
 - node_modules
 - _myfolder

That's my guess.

Upvotes: 2

Related Questions