Visual Studio Templates - custom parameters

2019-09-11 02:08发布

I am using VS 2015 templates to create a project for me, within my C# classes I have substitutions like $projectname$ and they work great if I name my project like this - MyTemplatedProject. I use $projectname$ for the part of class names and namespaces.

If I create generate a class like $projectname$Context, it becomes MyTemplatedProjectContext and all is well.

But if I name my project MyTemplatedProject.FrontEnd I have problems with the classes that are generated because they have the . in their name.

The substitution $projectname$Context becomes MyTemplatedProject.FrontEndContext and that does not work for a class name.

How do I create custom parameters based $projectname$, ideally I would have a parameter like $projectnameUpToFirstDot$ which only returns MyTemplatedProject when the project name is MyTemplatedProject.FrontEndContext?

2条回答
戒情不戒烟
2楼-- · 2019-09-11 03:01

If you just want to generate a valid class name based on the project name, instead of creating a custom template parameter, you can change $projectname$ to $safeprojectname$, which is documented as:

The name provided by the user in the New Project dialog box, with all unsafe characters and spaces removed.

查看更多
你好瞎i
3楼-- · 2019-09-11 03:13

I had exactly the same problem a week ago. I just needed some customed variables inside of my template, which would resolve in $projectname$ upper case and one other in lower case. Things like that.

It turned out for me to be the most effective and flexible way to develop my own project wizard using VS' custom wizard template.

Unless JavaScript & HTML is not a no-go for you, it is pretty easy to have some string manipulation on variables like $projectname$ there.

Once you set it up, go in default.js and edit in function

function onFinish()
{
    ...

    var prjName = wizard.FindSymbol('PROJECT_NAME');

    wizard.AddSymbol('PROJECT_NAME_WITHOUT_DOTS', prjName.split('.')[0]);

    ...
}

split('.') removes all dots and devides it into an array of strings. With [0] you select just the part up to the first dot.

In your template files you can then address the symbol PROJECT_NAME_WITHOUT_DOTS with the following syntax:

class [!output PROJECT_NAME_WITHOUT_DOTS] {
    ...
}
查看更多
登录 后发表回答