Using yeoman-generator variable inside generated template

1.6k views Asked by At

I am generating an angularJS project with yeoman. I call the generator with an argument and I get it from my main generator's script (index.js) by doing:

this.argument('name', { type: String });

I can use this parameter inside this same index.js by using:

this.options.name

Question: I want to use this same this.options.name inside my template, so that i can give its value to a variable. How can I do it?

2

There are 2 answers

7
quirimmo On BEST ANSWER

Define an angular constant and set it to this value. Then inside the controller associated to this view, just inject this constant.

myApp.constant('YEOMAN_NAME', MYVALUE);

Then just inject your constant inside the controller associated to your view, associate this constant to a scope variable and use it inside your template.

Now the "hardest" part is how to get this value inside the angular environment.

I don't know what is your index.js, I suppose that is only the main script associated to your page. In this case, if you do inside the main script something like

this.myVariable = 'myValue';

You are actually creating a new attribute to the window object (if you are not doing that inside some function)

So what you could do is to associate this variable to a window parameter, and try to be most specific as possible so you are not on risk to override something else in the window, like:

window.myYeomanName = this.options.name;

Then you can define your constant inside angular everywhere just doing:

myApp.constant('YEOMAN_NAME', window.myYeomanName);
0
chopeds On

To access a yeoman variable from Node.js, I did the following:

I renamed the file connections.js from sails, renamed it to _connections.js and placed it at the same level than sails folder inside the folder "templates" from yeoman's generator. Leaving it like this:

> yeomanGeneratorFolder 
>   |-app   
>      |-index.js   
>      |-templates
>        |-sails
>        |-_connections.js
>        |- ....

On the Generator's index.js. I created a function to write on a js file the data I needed. I sent a JSON object inside the copyTpl() function which contains the data I will need in the new file:

connections() {
      this.fs.copyTpl(this.templatePath('_connections.js'), this.destinationPath('./config/connections.js'),
      {
        dbName: this.item.dbName
      });
    }

In _connections.js I wrote:

database: '<%=dbName%>' //optional

Notice dbName is the key I gave to the JSON I sent inside the copyTpl() function in index.js.