Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Johannes Lantz 156 posts 838 karma points c-trib
    Mar 16, 2020 @ 11:01
    Johannes Lantz
    0

    Using IPublishedContent in razor helper method

    Hello everyone!

    I noticed that I use a code snippet in my template files very often. So to minimze code duplication I would like to make razor helper method of it. I would like it take the current model as a parameter. So my plan in to put it in "App_Code" to make it avaible to all template files. But when I us the following code:

    @inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    
    @helper DoStuff(IPublishedContent model){
            //Do stuff
        }
    

    I get the error message: "IPublishedContent could not be found found". I have tried to use some @using statements but I can't figure it out. Anything advice would help right now!

    Note: As of writing this, I noticed that I could use a partial view, passing in the model to get the result I want. But could always be useful to know for the future!

    Thanks!

    //Johannes

  • Aristotelis Pitaridis 84 posts 402 karma points
    Mar 16, 2020 @ 21:31
    Aristotelis Pitaridis
    100

    I like extensions so I will show you how to do it using extensions. If you want to put your code in App_Code, create the following class in this folder.

    using System.Web.Mvc;
    using Umbraco.Core.Models.PublishedContent;
    
    public static class MyExtension
    {
        public static MvcHtmlString GetTag(this IPublishedContent model)
        {
            TagBuilder h1 = new TagBuilder("h1");
            h1.InnerHtml = model.Name;
    
            return MvcHtmlString.Create(h1.ToString());
        }
    
        public static MvcHtmlString GetText(this IPublishedContent model)
        {
            return MvcHtmlString.Create(model.Name);
        }
    }
    

    This class contains two extensions. The first generates an h1 tag and puts the page name inside, and the second returns just the name of the page. In order to use it you will have to type the following lines

    @Model.GetTag()
    @Model.GetText()
    

    I hope it helps.

  • Johannes Lantz 156 posts 838 karma points c-trib
    Mar 18, 2020 @ 08:07
    Johannes Lantz
    0

    Hi Aristotelis!

    This is really useful! Thank you so much!

Please Sign in or register to post replies

Write your reply to:

Draft