Programmatically change templates

The requirement

I had the need to change 3000 legacy news articles from an old template to a new template. It could have been done manually of course but that would have taken days and where is the fun in that!

The solution

Please note: This is from an Umbraco 7 project and it may need changed slightly to work on Umbraco 8

Firstly I took the new styling and created a new template which inherited the correct Model so that I could strongly type my template.

@inherits Umbraco.Web.Mvc.UmbracoViewPage<ContentItem>

Next I mapped the old DocumentType properties to the new Style, things like the banner image was called headerImage in one template but bannerImage in the other. I was just aiming to make sure that everything would work when it had the new template applied to it.

I tested this on a single article to begin with and made sure that everything worked. Once I was happy that it did, it was time to code up a bit of script to do the move for all the other articles.

The handy thing for me was that the old articles had their own DocumentType, which meant I could target that specific DocumentType.

I then used the ContentService to find all the articles under a specific parent node, this meant I wasn't going to change anything that might not be within the section I needed to update.

The full code I used is here:

 var parent = Model.Parent.Id;

    var contentService = ApplicationContext.Current.Services.ContentService;
    var fileService = ApplicationContext.Current.Services.FileService;

    var template = fileService.GetTemplate("GenericContentItem");

    IList<IContent> allArticles = contentService.GetChildren(parent).ToList();

    foreach(var article in allArticles)
        if(article.ContentType.Alias == "contentItem")

            article.Template = template;

I placed this code in to a view and then hit that page from the frontend.

HOWEVER before I did that, I backed up my local database because if something went wrong and I needed to undo my changes, it was just quicker and eaiser to do that by restoring the database.

The code run over 3000+ articles in a matter of minutes and all articles with the DocumnetType Alias of contentItem were told to use the new GenericContentItem template that I had created earlier.

Once I had checked that everything had worked, I then deleted this bit of code from the view so that it doesn't run every single time someone visited the page!

The nice thing about this is if needed, I can manually swap back any node to use the old template with no issues.

I hope this is useful to someone and if you need any further information or are wondering what else you can do with the ContentService, check out the Umbraco documentation.

Happy coding!

Published on: 22 February 2021