Skip to content
This repository was archived by the owner on Feb 21, 2025. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,45 @@ fileinclude({
</ul>
```

### `loop` statement
index.html

```html
<body>
@@loop('loop-article.html', [
{ "title": "My post title", "text": "<p>lorem ipsum...</p>" },
{ "title": "Another post", "text": "<p>lorem ipsum...</p>" },
{ "title": "One more post", "text": "<p>lorem ipsum...</p>" }
])
</body>
```

loop-article.html
```html
<article>
<h1>@@title</h1>
@@text
</article>
```

### `loop` statement + data.json
data.json

```js
[
{ "title": "My post title", "text": "<p>lorem ipsum...</p>" },
{ "title": "Another post", "text": "<p>lorem ipsum...</p>" },
{ "title": "One more post", "text": "<p>lorem ipsum...</p>" }
]
```

loop-article.html
```html
<body>
@@loop("loop-article.html", "data.json")
</body>
```

### License
MIT

Expand Down
1 change: 1 addition & 0 deletions example/c/c.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
this is loop @@number
6 changes: 6 additions & 0 deletions example/index.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,9 @@ index

Defined in include @@param
}

@@loop('c/c.txt', [
{ "number": 1 },
{ "number": 2 },
{ "number": 3 }
])
8 changes: 8 additions & 0 deletions example/result/index.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,22 @@ example
Flatten object "@@obj"

Flatten variable "flatten param"

Defined in parent "success"
Context variable "example"

this is conditional

Flatten object "@@obj"

Defined in parent "success too"
Context variable "example"


Defined in include @@param


this is loop 1
this is loop 2
this is loop 3

85 changes: 85 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ module.exports = function(opts) {
name: 'include',
handler: includeHandler
});
text = replaceFunction(text, {
prefix: opts.prefix,
suffix: opts.suffix,
name: 'loop',
handler: loopHandler
});

function conditionalHandler(inst) {
// jshint ignore: start
Expand Down Expand Up @@ -143,6 +149,85 @@ module.exports = function(opts) {
return String(recFile.contents);
}
}


// Seriously: you need more commments in your codes -.-
function loopHandler(inst) {
var args = /[^)"\']*["\']([^"\']*)["\'](,\s*([\s\S]*())){0,1}\s*/.exec(inst.args);
var arr = [];

if (args) {

// loop array in the json file
if(args[3].match(/^('|")[^']|[^"]('|")$/)) {

// clean filename var and define path
var jsonfile = file.base + args[3].replace(/^('|")/, '').replace(/('|")$/, '');

// check if json file exists
if (fs.existsSync(jsonfile)) {
arr = require(jsonfile);
}
else {
return console.error("JSON file not exists:", jsonfile);
}

}
// loop array in the function
else {
try{
arr = JSON.parse(args[3]);
}
catch (err){
return console.error(err, args[3]);
}
}

// if everything is ok!
if(arr) {

var includePath = path.resolve(filebase, args[1]);
// for checking if we are not including the current file again
if (currentFilename.toLowerCase() === includePath.toLowerCase()) {
throw new Error('recursion detected in file: ' + currentFilename);
}

var includeContent = fs.readFileSync(includePath, 'utf-8');

if (opts.indent) {
includeContent = setIndent(inst.before, inst.before.length, includeContent);
}

// apply filters on include content
if (typeof opts.filters === 'object') {
includeContent = applyFilters(includeContent, args.input);
}

var recFile = new gutil.File({
cwd: process.cwd(),
base: file.base,
path: includePath,
contents: new Buffer(includeContent)
});

var contents = '';

for(var i in arr) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why for in?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typeof ... = object

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this case you should add check arr.hasOwnProperty(i) and maybe process array and object in different loops.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes... I was lazy in this case.

It could be better:

for(var i in arr) {
    if(arr.hasOwnProperty(i)) {
        var context = arr[i];
        recFile = include(recFile, includeContent, args[3] ? context : {});
        if(typeof context == 'object') {
            context['_key'] = i;
        }
        contents += String(recFile.contents);
    }
}

Works with array or object. Flexible is better:
https://jsfiddle.net/webarthur/60ayy87z/1/

if(arr.hasOwnProperty(i)) {
var context = arr[i];
recFile = include(recFile, includeContent, args[3] ? context : {});
// why handler dont reconize underscore?
// if(typeof context == 'object' && typeof context['_key'] == 'undefined') {
// context['_key'] = i;
// }
contents += String(recFile.contents);
}
}
}
return contents;
}
}


file.contents = new Buffer(text);

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
],
"author": "haoxin",
"contributors": [
"Bogdan Chadkin <trysound@yandex.ru>"
"Bogdan Chadkin <trysound@yandex.ru>",
"Arthur Araújo <webarthur@gmail.com>"
],
"license": "MIT",
"devDependencies": {
Expand Down