How do I create a list of data based on actual twig files within project

*爱你&永不变心* 提交于 2019-12-11 14:17:41

问题


I am creating an app via NPM using https://www.npmjs.com/package/grunt-twig-render. It essentially is twig.js. I'm keeping it slim, so right now there isn't any other php or anything like that. Just npm / twig.js and other npm packages, including Grunt.

Here's what I'm trying to do. Right now, I have a bunch of twig files within subfolders of a directory.

What I'd like to do is generate a list of data of the .twig files in that subdirectory. Something like this may work well

files: [
{
"name": "file1.twig"
"path": "/folder1"
},
{
"name": "file2.twig"
"path": "/folder1"
},
{
"name": "file3.twig"
"path": "/folder1"
}
]

But I'm not super picky. Just seeing if anyone has found a way to create a list of files within a folder via npm, or twigjs, or something similar.

If it generates a .json file, that would be ideal. This would be part of a build process, so doing that via Grunt would work well too.

Thank you in advance


回答1:


You can register a custom grunt task in your Gruntfile.js which utilizes the shelljs find method to retrieve the path of each .twig file.

shelljs is a package which provides portable Unix shell commands for Node.js. It's find method is analogous to the Bash find command.

The following steps describe how to achieve your requriement:

  1. cd to your project directory and install shelljs by running:

    npm i -D shelljs
    
  2. Configure your Gruntfile.js as follows:

    Gruntfile.js

    module.exports = function(grunt) {
    
      // requirements
      var path = require('path'),
        find = require('shelljs').find;
    
      grunt.initConfig({
        // other tasks ...
      });
    
      /**
       * Custom grunt task generates a list of .twig files in a directory
       * and saves the results as .json file.
       */
      grunt.registerTask('twigList', 'Creates list of twig files', function() {
        var obj = {};
    
        obj.files = find('path/to/directory')
            .filter(function(filePath) {
              return filePath.match(/\.twig$/);
            })
            .map(function(filePath) {
              return {
                name: path.basename(filePath),
                path: path.dirname(filePath)
              }
            });
    
        grunt.file.write('twig-list.json', JSON.stringify(obj, null, 2));
      });
    
      grunt.registerTask('default', ['twigList']);
    };
    

Explanation

  1. Both shelljs and nodes built-in path module are required into Gruntfile.js.

  2. Next a custom task named twigList is registered.

    • In the body of the function we initialize an empty object and assign it to a variable named obj.

    • Next, the shelljs find method is invoked passing in a path to the subdirectory containing the .twig files. Currently the path is set to path/to/directory so you'll need to redefine this path as necessary.

      Note: The find method can also accept an array of multiple directory paths as an argument. For example:

      find(['path/to/directory', 'path/to/another/directory'])
      
    • The find method returns an Array of all paths found inside the given directory, (many levels deep). We utilize the Array's filter() method to return only filepaths with a .twig file extension by providing a regex (\.twig$) to the Strings match method.

    • Each item of the resultant Array of .twig filepaths is passed to the Array's map() method. It returns an Object with two properties (name and path). The value for the name property is obtained from the full filepath using nodes path.basename() method. Similarly, the value for the path property is obtained from the full filepath using nodes path.dirname() method.

    • Finally the grunt file.write() method is utilized to write a .json file to disk. Currently the first argument is set to twig-list.json. This will result in a file named twig-list.json being saved to the top-level of your project directory where Gruntfile.js resides. You'll need to redefine this output path as necessary. The second argument is provided by utilizing JSON.stringify() to convert obj to JSON. The resultant JSON is indented by two spaces.

Additional info

As previously mentioned the shelljs find method lists all files (many levels deeep) in the given directory path. If the directory path provided includes a subfolder(s) containing .twig files that you want to exclude you can do something like the following in the filter() method:

.filter(function(file) {
    return filePath.match(/\.twig$/) && !filePath.match(/^foo\/bar/);
})

This will match all .twig files, and ignore those in the sub directory foo/bar of the given directory, e.g. path/to/directory.



来源:https://stackoverflow.com/questions/51661546/how-do-i-create-a-list-of-data-based-on-actual-twig-files-within-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!