简体   繁体   中英

Select “umbraco item” using razor

I want to write a razor macro MySelectMacro that selects which umbraco:item to be rendered.

my simple structure for this case is two pages -MasterPage and TextPage- and the TextPage contains two fields of type rich-text editor -field_1 and field_2-

this is my try which don't work,

Here is the TextPage template:

<asp:Content ContentPlaceHolderId="MainPageContent" runat="server">
        <umbraco:Macro Alias="MySelectMacro" runat="server" />
</asp:Content>

and here is the macro MySelectMacro :

@if (condition)
{
    <umbraco:Item field="field_1" runat="server" />
}
else
{
    <umbraco:Item field="field_2" runat="server" />
}

nb: I'm new in umbraco and razors

You cannot use server tags inside your razor template. tags like:

<umbraco:Item field="field_1" runat="server" />

But you can call

@Model.field_1

Final version should look like that:

@if (condition)
{
    @Model.field_1
}
else
{
    @Model.field_2
}

Check this post about razor macros in umbraco: http://www.diplo.co.uk/blog/2011/6/17/using-razor-in-umbraco-47.aspx

I just stumbled over this answer and for others reading like me: in 2015 and later, it's not @Model.field but @Dictionary["field"] .

It's explained here:

https://our.umbraco.org/documentation/reference/templating/macros/razor/using-dictionary-items

Anyway, embraced by quota and bracket your field name does not disturb the rest of the ASP script, even if it contains special characters.

You can't mix WebForm and Razor syntax!

The equivalent of the old umbraco:item in the new Razor syntax would be:

@Umbraco.Field("field_1")

You can also pass in various parameters, including the strip paragraph tags flag:

@Umbraco.Field("field_1", removeParagraphTags = true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM