AlpineJS Workflow

I’ve had a read of the docs and forum but I cant seem to find an effective workflow for Alpine JS + Hugo.

Here’s what I’m trying to achieve.

I have a page in content, ./content/page.html

Inside that page I would like to set up a function with a data object for Alpine eg.

<div x-data="myFunc()" class="my-thing">
    <span x-text="key"></span>
</div>

<script>
function myFunc() {
    return {
        "key" : "value",
        "key2" : "value2",
        ...,
        click() { <!-- do something on click --> },
}
</script>

Where I am getting stuck.

I have a huge data object (key/value pairs), let’s say 1000 items, so I dont want to drop them in there, instead I would like to store them in ./data/mydata.json and then call them into the page.

I understand that I can’t do this:

<script>
function myFunc() {
    return {
        {{ .Site.Data.myjson | jsonify | safeJS }},
        click() { <!-- do something on click --> },
}
</script>

Because:

  1. The curly braces mess things up
  2. You cant access .Site.Data from content pages.

I assume I need to move this to a shortcode or something, but this is where I am getting lost.

I assume people have faced this issue using Alpine / Vue etc before which is why Im a bit flummoxed that I cant find a solution on the forums.

Hoping someone has the answer. Thanks for reading.

The “items” in the return block need to be named functions/objects, so this should work:

function myFunc() {
    return {
       data:  {{ .Site.Data.myjson | jsonify | safeJS }},
       click() { <!-- do something on click --> },
}

Note that I haven’t really tested the above, but I don’t see how your original solution would work.

That said, I find it nicer to work with JS code in external JS files. With Alpine’s global it can be a little hard to manage at scale, but it also fits nicely into Hugo’s limited JS bundling support.

What I have been doing when testing out Alpine is:

  1. Create a JS file with all the data/config objects in JS global variables and load that first with ExecuteAsTemplate, e.g.

var myData= {{ site.Params.my_data | jsonify | safeJS }};
var myData2= {{ site.Params.my_data2 | jsonify | safeJS }};

  1. Pass that into the function when creating the Alpine component:
<div x-data="myFunc(myData)">

As to shortcodes, there are plenty of docs about that, but I don’t see the relevance.

1 Like