Skip to content

Commit

Permalink
feat: allow json parsing in templates (#39)
Browse files Browse the repository at this point in the history
Useful for loops and what not.
  • Loading branch information
btkostner authored Apr 12, 2024
1 parent 0800b65 commit 6b2ea9b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,20 @@ In some instances you may want to allow only certain files to be rendered. This
{{~#if DO_NOT_RENDER_THIS_FILE}}{{denyRender}}{{/if~}}
```

### JSON Variables

Normal variables are basic strings. In some cases you want to use JSON objects or arrays so you can loop over them. This can be achieved by using the `jsonParse` helper.

```handlebars
{{jsonParse MY_JSON_ARRAY}}
```

```handlebars
{{#each (jsonParse MY_JSON_ARRAY)}}
{{this}}
{{/each}}
```

## Alternatives

There are many other git sync type actions currently on GitHub, however most of them only handle static files. This action was created where some files are dynamic and should be templated or scripted before synced.
14 changes: 14 additions & 0 deletions src/handlebars.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,17 @@ describe.concurrent("handlebars denyRender", () => {
expect(() => template({})).not.toThrowError(DenyRenderError);
});
});

describe.concurrent("handlebars jsonParse", () => {
it("allows loops from json variables", async (_ctx) => {
const template = Handlebars.compile(
"{{#each (jsonParse MY_JSON_ARRAY)}}{{prop}} and {{/each}}",
);

const result = template({
MY_JSON_ARRAY: '[{"prop":1},{"prop":2},{"prop":3}]',
});

expect(result).toEqual("1 and 2 and 3 and ");
});
});
4 changes: 4 additions & 0 deletions src/handlebars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,8 @@ Handlebars.registerHelper("denyRender", function () {
throw new DenyRenderError();
});

Handlebars.registerHelper("jsonParse", function (jsonString, _options) {
return JSON.parse(jsonString);
});

export default Handlebars;

0 comments on commit 6b2ea9b

Please sign in to comment.