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

Added support of custom template filters #49

Closed
wants to merge 1 commit into from

Conversation

liverenemy
Copy link

@liverenemy liverenemy commented Aug 2, 2017

There was an issue with using this project with generated models.

I have the following section in my custom-data.js file:

Role: {
        hasMany: {
            FkUserRoleIdRoleRoleIdRoles: {
                as: 'users'
            }
        },
        belongsTo: {},
        getterMethods: {
            isApplicant: function () {
                return this.getDataValue('name') == 'applicant';
            },
            isAssistant: function () {
                return this.getDataValue('name') == 'assistant';
            },
            isCustomer: function () {
                return this.getDataValue('name') == 'customer';
            }
        }
    },

These getter methods weren't correctly exported to the resulting Role model because of unthoughtfully working 'stringifyIfObject' filter: it returned an empty object or a string in different variations of getter methods.

So I decided to add an ability to create own template filters inside of 'util/template-filter.js' file of the template folder (not the pg-generator folder!).
This pull request adds new nunjucks filters and makes them available for use with model generating template.

As for me, this new filter totally fixed the issue with getter methods:

const addFilters = nunjucksEnvironment => {
    nunjucksEnvironment.addFilter('dumpWithMethods', function (obj, cpaces) {
        const getMethods = (obj) => {
            let result = [];
            for (let id in obj) {
                try {
                    if (typeof(obj[id]) == "function") {
                        result.push(id + ": " + obj[id].toString());
                    } else {
                        result.push(`${id}: ${JSON.stringify(obj[id], null, spaces)}`);
                    }
                } catch (err) {
                    result.push(id + ": inaccessible");
                }
            }
            return result;
        };

        return `{${getMethods(obj).join(',')}}`;
    });
};

So the following change in 'table/definition/{table.name # dashCase}.js.nunj.html' totally fixed the issue using the newly created filter:

        {% for key, value in c -%} {# Custom table details from custom data not found in template #}
            {%- if (templateDataFields.indexOf(key) == -1) -%}
                ,{{ key }}: {{ value | dumpWithMethods }}
            {% endif -%}
        {% endfor -%}

How to use

Simply add a 'template-filter.js' file into the 'util' subdirectory of your template folder and write the code just as following:

const addFilters = env => {
    env.addFilter('square', value => value * value);
};

module.exports.addFilters = addFilters;

And then you can use the new filter in your templates:

{% set val = 4 %}
{{val | square}}

Simply add a 'template-filter.js' file into the 'util' subdirectory of your template folder and write the code just as following:
```javascript
const addFilters = env => {
    env.addFilter('square', value => value * value);
};

module.exports.addFilters = addFilters;
```

And then you can use the new filter in your templates:

```nunjucks
{% set val = 4 %}
{{val | square}}
```
@ozum
Copy link
Owner

ozum commented Jan 13, 2018

@liverenemy somehow I missed this PR. Sorry for late answer. Could you please add some documentation?

@ozum ozum closed this Apr 29, 2019
@iggh
Copy link

iggh commented May 26, 2020

Shame this has been closed. This would be a useful addition for a filter such as: mozilla/nunjucks#313 (comment)

What specifically was missing from it? Were you happy with the PR, it was just missing documentation?

@ozum
Copy link
Owner

ozum commented May 26, 2020

@iggh, GitHub didn't send me notifications when PR is created because of a setting. I realized that PR 6 months later and requested documentation from OP. After such a time @liverenemy, most probably forgot this PR.

If you would like to recreate it with documentation, please welcome.

Actually pg-generator need a heavy overhaul. I would like to release a new major version with following features:

  • Plugin support, so everyone can develop it's own templates easier,
  • Use of latest version of pg-structure,
  • Modern documentation infrastructure such as VuePress,
  • jest tests,
  • TypeScript,

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

Successfully merging this pull request may close these issues.

None yet

3 participants