Search code examples
sitecoresitecore-mvc

Accessing Sitecore template field values


This may be documented somewhere, but I cannot find it.

I am using the Sitecore helper and razor syntax to place values into my view:

@Html.Sitecore().Field("foo"); 

This works fine, but, I have Fields defined in Groups, and a few of them have the same name, like:

Group1: foo

Group2: foo

Question: Is there any way to access the field by group? Something like this (what I have already tried):

@Html.Sitecore().Field("Group1.foo");

Solution

  • As long as I know it is not possible to use the sections name.

    I would avoid to have the same field name even between differents sections.

    Or a option is to pass the field ID and then create classes or constants to not hard code IDs

    @Html.Sitecore().Field("{E77E229A-2A34-4F03-9A3E-A8636076CBDB}");
    
    or
    
    @Html.Sitecore().Field(MyTemplate.MyGroup.Foo); //where foo returns the id.
    

    EDIT:

    MyTemplate.MyGroup.Foo would be classes/structs you created your own just to make easier and more reliable the references all over you project. (you can use a tool to auto-generate it like a T4 template)

    public static struct MyTemplate
    {
        public static struct MyGroup1
        {
            public static readonly ID Foo = new ID("{1111111-1111-1231-1231-12312323132}");
        }
        public static struct MyGroup2
        {
            public static readonly ID Foo = new ID("{9999999-9999-xxxx-1231-12312323132}");
        }
    }