Skip to content

Commit 5f27fd4

Browse files
committed
feat: Lift attrs to toplevel when gen data context
1 parent 2dd41ea commit 5f27fd4

1 file changed

Lines changed: 19 additions & 2 deletions

File tree

src/sphinxnotes/data/data.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -222,8 +222,25 @@ class Data:
222222
attrs: dict[str, Value]
223223
content: Value
224224

225-
def ascontext(self) -> dict[str, Any]:
226-
return asdict(self)
225+
def ascontext(self, lift_attrs: bool = True) -> dict[str, Any]:
226+
"""
227+
Convert Data to a dict for usage of Jinja2 context.
228+
229+
:param lift_attrs:
230+
Whether life the attrs to top-level context when there is no key
231+
conflicts. For example:
232+
233+
- You can access ``Data.attrs['color']`` by "{{ color }}"" instead
234+
of "{{ attrs.color }}".
235+
- You can NOT access ``Data.attrs['name']`` by "{{ name }}" cause
236+
the variable name is taken by ``Data.name``.
237+
"""
238+
ctx = asdict(self)
239+
if lift_attrs:
240+
for k, v in self.attrs:
241+
if k not in ctx:
242+
ctx[k] = v
243+
return ctx
227244

228245

229246
@dataclass

0 commit comments

Comments
 (0)