3
votes

I'm trying to return a formatted date from a razor template in umbraco. I'm not sure how to get a value from a field defined in a parameter though.

Here is the code I'm playing with. The field I'm passing in is called "articleDate". I'm getting the parameter value output, however when I try to get the value of the field using the parameter name it returns nothing. If I ask for the value by the field name itself, that works. How can I create a generic macro like this?

@{var param = @Parameter.dateField;}
Field Name: @param
<br/>
Field Value: @Model.param
<br/>    
Field Value: @Model.articleDate

I tried using @Model.GetDynamicMember(..) as well, but that just throws an exception.

Field Value: @Model.GetDynamicMember("articleDate");​

Error loading Razor Script getDate.cshtml
Cannot invoke a non-delegate type

Can someone point me in the right direction? I'm just trying to create a simple macro I can use to format dates across my page.

Is it possible to pass the value of my date directly into the razor macro? This is how I'm currently calling it:

<umbraco:Macro ID="Macro1" Alias="getDate" dateField="articleDate" runat="server"></umbraco:Macro>
1

1 Answers

6
votes

If you call your Macro like you wrote:

<umbraco:Macro ID="Macro1" Alias="getDate" dateField="articleDate" runat="server"></umbraco:Macro>

You're actually passing the name of the field "articleDate". In the macro, you then may get the value of the Model's articleDate property by using:

Field Value: @Model.getProperty(Parameter.dateField).Value

Instead of macro's I also recommend using helpers or - for more complex scripts - RenderPage. A nice writeup can be found here: http://joeriks.wordpress.com/2011/03/11/better-structure-for-your-razor-scripts-with-renderpage-in-umbraco/

Example:

@helper GetDate(dynamic dateField)
{
     @dateField.ToString("[yourFormat]")
}

You may pass parameters to scripts rendered with RenderPage by using the Page object:

<umbraco:macro language="razor" runat="server">
@{
    Page.dateField=Model.articleDate;
}
@RenderPage("~/macroscripts/getdate.cshtml")
</umbraco:macro>

getdate.cshtml:

@Page.datefield.ToString("[yourFormat]")