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

feat: dynamic localsDefaults #424

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

Conversation

francoislevesque
Copy link

@francoislevesque francoislevesque commented Mar 24, 2023

Context

We want to dynamically inject new variables to the locals object depending on the user's input. This is useful for several reasons.

  1. We want to automatically generate variations of an argument to lighten the templates' code.
    a. For exemple, if a user inputs --name 'OrderLine', we want to dynamically add :

    • myName : "orderLine"
    • my_name : "order_line"
    • MyName : "OrderLine"
    • myNameS : "orderLines" (forced plural)
    • my_nameS : "order_lines" (forced plural)
    • MyNameS : "OrderLines" (forced plural)

    This allows us the replace the following code :

    // less lisible
    let <%= h.camelCase(h.plural(model)) %>
    
    // increased lisibility
    let <%= myNameS %>
  2. We can add dynamic variables depending of the user arguments. Internally, we built a 20 field type generators (for input text, select, date picker, autocomplete, etc). Depending on the given field type, we want to make new variables accessible in the template. We prefer this approach over helpers because it makes the code a bit more readable, but also a lot faster. We use complex helpers to add dynamic variables available to the templates, but these are recalculated everytime they are called. Having more than 200 templates, this will greatly improve DX and performance!

How to use

// .hygen.js

module.exports = {
  templates: `${__dirname}/.hygen/templates`,
  localsDefaults(locals, config) {
    return {
      myModel: changeCase.camelCase(locals.model ?? ""),
    };
  },
}

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

1 participant