CDSoft / pp

PP - Generic preprocessor (with pandoc in mind) - macros, literate programming, diagrams, scripts...
http://cdelord.fr/pp
GNU General Public License v3.0
252 stars 21 forks source link

Could you add a for-construct? #27

Closed AndreVanDelft closed 6 years ago

AndreVanDelft commented 7 years ago

Would it be possible to add support for for-loops. E.g.,

!for(example)(!code.gui)
### Example: GUI - ${example.title}
`` `scala
!example.src
`` `
!endfor

This would be fed with data from a YAML file, e.g.,

code:
  gui:
    traditional:
      title: Traditional Approach
      src: |
        def ...
        val ...

    alternative:
      title: Alternative Approach
      src: |
        def ...
        val ...

  controller:
     ...

The result would then be like:

### Example: GUI - ${Traditional Approach}
`` `scala
        def ...
        val ...
`` `

### Example: GUI - ${Alternative Approach}
`` `scala
        def ...
        val ...
`` `

Apart from the for-construct itself, I am requesting support for:

tajmone commented 7 years ago

Interesting feature request @AndreVanDelft ! It might also take a similar approach as the one used by mustache:

https://mustache.github.io/mustache.1.html

Mustache can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object.

We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values. This document explains the different types of Mustache tags.

... which can achieve the same results without the need of for loops.

A possible approach — not requiring the introduction of a YAML parser into PP — might consist in implementing a built-in macro to interface with mustache, or to introduce in PP's parsers awareness of mustache's tags delimiters ({{ }}), and pass them on to mustache.

If I understand correctly, this feature wouldn't require preserving these values in some namespace: they would be created and emitted for the lifetime of the loop, and then discarded from memory.

CDSoft commented 6 years ago

If the goal is to loop over yaml file I think a more generic solution is to use a yaml parser. For instance you can use an (embedded) python script importing the PyYAML module. You will get the power of a real programming language for free.

For example:

\python3
~~~
import yaml
code = yaml.load(open('/tmp/test.yaml'))

for example in code['code']['gui'].values():
    print("""\
### Example: GUI - %s
```scala
%s
```
""" % (example['title'], example['src']) )
~~~
CDSoft commented 6 years ago

No feedback. I guess the workaround is accepted or the need is not so strong. I propose to close this issue.