18, the first day of the new year to work, diligent yards farmers, but also began a year of labor. Brushed the dust on the keyboard, think of years ago, MVCT4 template custom knowledge points, today a little summary.
Not much to say, first open vs Create an MVC project to run successfully. Ok! Now let's go to create a new view and see the following dialog box
When we create a view, vs lists the following templates to choose from, where do these templates come from?
Win+e Quick Access Navigate to Folder C:\Program Files (x86) \microsoft Visual Studio 14.0\common7\ide\extensions\microsoft\web\mvc\ Scaffolding\templates\mvcview
You can see
Is it a familiar feeling? Ha ha. Yes, the view template provided by VS is from here. So the question is, what if we want to define the template ourselves?
In fact, the method is very simple, based on the MVC extension mechanism, as long as we build the Codetemplates folder at the root of our project, and then copy all the files under templates, then when the project builds the view, there is Codetemplates folder in the VS Discovery project. , it will be read first.
You can also create a template folder through NuGet packages. Specific steps
After installation
The project will automatically download the pre-made template.
Now that we know the specific read location of the template, let's take a look at what's in it and how it generates code. Open the List.cs.t4 file under Mvcview.
You can see what's inside:
Of course, when you open, should not be highlighted, just a plain text, there is no smart hint. All, here's to a VS integration tool for writing T4 templates, I highly recommend
T4editor:http://t4-editor.tangible-engineering.com/download_t4editor_plus_modelingtools.html
Select the corresponding version, after downloading the installation, open the T4 template file again, you will find that the code is highlighted, smart hints are also reproduced, a bit more cordial!!
Well, to get to the point, we want to customize our own template, so what is the template syntax? Let's put it down first, we'll copy List.cs.t4, do not modify anything, change the name to MyList.cs.t4,
OK, now let's go to the new view and see the popup dialog box:
You will find that the MyList template has been read. Next, it is good to do, as long as the contents of the inside, modified into our own logic, then it is done!
So specific grammar instruction knowledge, you can refer to this man's induction: https://www.cnblogs.com/fenglingyi/p/5925383.html.
I am here to change the title of the template symbolically, to see the effect:
Modify the MyList.cs.t4 custom title, and then display the title.
New View:
After clicking Add, you will find that the generated cshtml file
The title here is what we define in the template.
Okay, here's the idea. So exactly T4 template underlying mechanism, is how to generate code snippets, and later on ~ ~
MVC Custom T4 Template Chapter