Copied to clipboard

Flag this post as spam?

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


  • Anton 36 posts 67 karma points
    May 25, 2012 @ 12:12
    Anton
    0

    Best place to create reusable snippets of code?

    Hi,

    I starting to expand my template library and i'm started identified some areas where i would like to abstract away some repetitive code:

    @inherits RenderViewPage
    @using System.Web.Mvc.Html;
    @using Umbraco.Cms.Web;
    @{
    Layout = "_Layout.cshtml";
    ViewBag.Title = @Umbraco.Field("pageTitle");
    ViewBag.MetaKeywords = @Umbraco.Field("metaKeywords");
    ViewBag.MetaDescription = @Umbraco.Field("metaDescription");
    }

     

    In the above example the Meta Data is used across every template in my website.  How i abstract those 3 lines of code into a snippet(?) so it can be called with a single line of code OR can it be hardcoded in a controller somewhere?

    Thanks

     

  • Grant Thomas 291 posts 324 karma points
    May 25, 2012 @ 12:20
    Grant Thomas
    0

    You could create a Partial script to manage the metadata only, and then call it pretty easily. Something like this:

    Partial named Metadata:

    @{
    ViewBag
    .Title=@Umbraco.Field("pageTitle");
    ViewBag.MetaKeywords=@Umbraco.Field("metaKeywords");
    ViewBag.MetaDescription=@Umbraco.Field("metaDescription");

    I do this differently, though, by just outputing the <meta name="x" content="y" /> tags.

    Calling from template:

    @Html.Partial(metadata)
  • Michael Latouche 504 posts 819 karma points MVP 4x c-trib
    May 25, 2012 @ 13:44
    Michael Latouche
    0

    Hi,

    I think you can also put these 3 lines of codes in your _Layout.cshtml file, assuming this is the "root" layout of all your views.

    Cheers,

    Michael.

  • Anton 36 posts 67 karma points
    May 25, 2012 @ 16:18
    Anton
    0

    Putting the code in _Layout.cshtml will cause a runtime error - Here's my code:

    <title>@Umbraco.Field("pageTitle")</title>
    <meta name="keywords" content="@Umbraco.Field("metaKeywords")"/>
    <meta name="description" content="@Umbraco.Field("metaDescription")"/>

     

     

Please Sign in or register to post replies

Write your reply to:

Draft