Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@foreach loops can only have one parameter #101

Open
knight666 opened this issue Jan 26, 2016 · 1 comment
Open

@foreach loops can only have one parameter #101

knight666 opened this issue Jan 26, 2016 · 1 comment

Comments

@knight666
Copy link

I'm writing a personal project using Node.JS and use preprocess to generate HTML from templates. For the most part, I'm very pleased with how this has turned out: I can generate my entire website with a single grunt command. However, one issue has come up time and time again: for loops really aren't that useful.

One of my pages generates a link to each of my projects, using a styled HTML list, like this:

<ul>
    <li><a href="projects/project1.html">Project 1</a></li>
    <li><a href="projects/project1.html">Project 1</a></li>
    <li><a href="projects/project1.html">Project 1</a></li>
</ul>

The problem is that I cannot generate this list using preprocess. I can wrap the block in a @foreach loop, like so:

<ul>
<!-- @foreach $PROJECT in PROJECTS_LIST -->
    <li><a href="projects/project1.html"><!-- @echo $PROJECT --></a></li>
<!-- @endfor -->
</ul>

But I think you can already spot the problem: I need a parameter for both the link and the project title and I can only ever have one. There are no string splitting functions in the syntax, so I can't even hack in a second parameter by splitting a string on a predetermined character. So I end up writing code like this:

// Grunt task

project_list.forEach(function(project) {
    context['PROJECT_LIST'] += '<li><a href="projects/' + project.link + '">' + project.link + '</a></li>\n';
});

// Template

<ul>
    <!-- @echo PROJECT_LIST -->
</ul>

This works, but this basically means the @foreach has no use for my project. In my opinion, the loop could be more useful if it supported syntax like this:

<ul>
<!-- @for { $LINK, $TITLE } in PROJECTS_LIST -->
    <li><a href="projects/<!-- @echo $LINK -->"><!-- @echo $PROJECT --></a></li>
<!-- @endfor -->
</ul>

In order to keep the syntax sane and prevent the module from growing into a full-blown scripting language, I would add the requirement that the iterated values can only be strings or numbers, not lists or objects.

@shushenghong
Copy link

+1, need simple loop support in origin html source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants