Need help implementing an Orchard CMS Shape Method

2019-08-22 03:37发布

问题:

I am just learning Orchard CMS and am having trouble implementing a shape method to return some arbitrary text without creating a whole set of model, driver, etc.

I am trying to use the code at http://docs.orchardproject.net/Documentation/Accessing-and-rendering-shapes

public class DateTimeShapes : IDependency {
private readonly IClock _clock;

public DateTimeShapes(IClock clock) {
    _clock = clock;
    T = NullLocalizer.Instance;
}

public Localizer T { get; set; }

[Shape]
public IHtmlString DateTimeRelative(HtmlHelper Html, DateTime dateTimeUtc) {
    var time = _clock.UtcNow - dateTimeUtc;

    if (time.TotalDays > 7)
        return Html.DateTime(dateTimeUtc, T("'on' MMM d yyyy 'at' h:mm tt"));
    if (time.TotalHours > 24)
        return T.Plural("1 day ago", "{0} days ago", time.Days);
    if (time.TotalMinutes > 60)
        return T.Plural("1 hour ago", "{0} hours ago", time.Hours);
    if (time.TotalSeconds > 60)
        return T.Plural("1 minute ago", "{0} minutes ago", time.Minutes);
    if (time.TotalSeconds > 10)
        return T.Plural("1 second ago", "{0} seconds ago", time.Seconds);

    return T("a moment ago");
}

However, I am not entirely sure where this should go. I have tried putting it both in a controller and in a model with unsuccessful results.

So, my question is, where should this code be placed? And what is the correct way to call it from a template?

回答1:

You can just place this code in a class called Shapes.cs or DateTimeShapes.cs (not necessary, but kind of a convention with Orchard)

You can then use it in your views like this:

@{
    var date = DateTime.Now;
}

@Display.DateTimeRelative(date)