Skip to content

Commit

Permalink
feat: allow to define custom data for partials (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmjuanes authored Feb 5, 2025
1 parent 9c451f1 commit 9eeb092
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 3 deletions.
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,35 @@ const result = m("{{>>foo}}Bob{{/foo}}", {}, options);
// Output: 'Hello Bob!'
```

#### Partials data

> This feature was added in `v0.18.0`.
Partials allows you to define custom data. Instead of providing a string with the partial content, you can provide an object with the following keys:

- `body`: a string with the partial content.
- `data`: an object with your custom data for the partial. You can also use `attributes` as an alias.

Custom data will be available in the partial content as a variable `@partial`.

Example:

```javascript
const options = {
partials: {
foo: {
body: "Hello {{@partial.name}}!",
data: {
name: "Bob",
},
},
},
};

const result = m("{{> foo}}", {}, options);
// Output: 'Hello Bob!'
```

### Inline partials

> This feature was added in `v0.16.0`.
Expand Down
10 changes: 7 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,14 @@ const create = (template = "", options = {}) => {
if (tokens[i].startsWith(">>")) {
i = compile(tokens, blockContent, context, vars, i + 1, t);
}
if (typeof partials[t] === "string") {
if (typeof partials[t] === "string" || typeof partials[t]?.body === "string") {
const newCtx = args.length > 0 ? args[0] : (Object.keys(opt).length > 0 ? opt : context);
const newVars = {...vars, content: blockContent.join("")};
compile(tokenize(partials[t]), output, newCtx, newVars, 0, "");
const newVars = {
...vars,
content: blockContent.join(""),
partial: partials[t]?.attributes || partials[t]?.data || {},
};
compile(tokenize(partials[t]?.body || partials[t]), output, newCtx, newVars, 0, "");
}
}
else if (tokens[i].startsWith("=")) {
Expand Down
12 changes: 12 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,18 @@ describe("templating", () => {
};
assert.equal(m("{{>foo userName=name}}", data, {partials}), "Hello Bob!");
});

it("should allow partial variables", () => {
const partials = {
foo: {
body: "Hello {{@partial.name}}!",
attributes: {
name: "Bob",
},
},
};
assert.equal(m("{{> foo}}", {}, {partials}), "Hello Bob!");
});
});

describe("{{< xyz}}", () => {
Expand Down

0 comments on commit 9eeb092

Please sign in to comment.