Skip to content

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.

1 participant