jgm/doctemplates

Cannot access outer loop variables in templates with nested loops

mfsch opened this issue · 3 comments

mfsch commented

In the example below, I would expect that $pages.slug$ always refers to the item of the outer loop, even inside the inner loop. From what I could gather, there appears to be no way to access the outer slug from within the inner for loop. Is this the expected behavior?

data.md:

---
title: nested arrays
pages:
  - slug: page-1
    subpages:
      - slug: subpage-1
      - slug: subpage-2
  - slug: page-2
    subpages:
      - slug: subpage-1
      - slug: subpage-2
---

template.md:

$for(pages)$
/$pages.slug$
$for(pages.subpages)$
  /$pages.slug$/$pages.subpages.slug$
$endfor$
$endfor$
$ pandoc --template=template.md data.md
/page-1
  /subpage-1/subpage-1
  /subpage-2/subpage-2
/page-2
  /subpage-1/subpage-1
  /subpage-2/subpage-2
$ pandoc --version
pandoc 2.11.2
Compiled with pandoc-types 1.22, texmath 0.12.0.3, skylighting 0.10.0.3,
citeproc 0.2, ipynb 0.1.0.1
User data directory: /home/mfsch/.local/share/pandoc or /home/mfsch/.pandoc
Copyright (C) 2006-2020 John MacFarlane. Web:  https://pandoc.org
This is free software; see the source for copying conditions. There is no
warranty, not even for merchantability or fitness for a particular purpose.
jgm commented

I need to look into this; it isn't intended.

jgm commented

I see why this is happening. We're using "it" in the context map to hold the current value of the variable as we iterate through. So of course the variable in the inner loop overwrites the outer one.

Indeed, the variable we iterate on is actually replaced by "it" in the parsing stage.

Obviously, this needs rethinking.

mfsch commented

Thank you for the fix, and your work on pandoc in general @jgm !