sitefinitysitefinity-10

Get blog post custom field in template head - Sitefinity


I need to set several meta tag values in my page head to values set in blog post custom fields.

How do I access the blog item viewmodel from the head?

I've created a separate MVC view snippet for my custom head and referenced it in my template's layout, that much works.

Tried

I grab some of the same custom field values inside my blog template via references like Model.Item.Fields.MyFieldName.Fields.Title.

Adding this same line to the head template throws a System.Web.HttpCompileException with little useful information attached. I somewhat expected this, as I suspect that viewmodel for the blog post only exists in the context of the blog widget.

Ends up that I need to rebuild after every change to the head cshtml file or I get this error. Seeing as this is about a four-minute process with Sitefinity (15 seconds to build, 3:45 to do whatever Sitefinity does for about four minutes), this is a gruelingly horrid thing to have to do.

However the Model is null at this level.

Also tried

Per the ever-helpful and highly knowledgeable @Veselin Vasilev, I looked into passing the data up via MetaDataFields. I didn't see these options in my admin section for the widget. To clarify, I'm using the built-in "Blog posts" widget with a customized view file.

The advanced edit view

enter image description here

But if it's possible to do this, it gives me hope that there's a way to pass more data up, even if it's going to take some work.


Solution

  • EDIT: Sitefinity v.10.2 and above:

    There is an easier way to achieve what you are trying - in Page edit mode, in the Blog Posts widget click Edit and then Advanced. Then you should see a MetaDataFields button. Click it and you should see several meta data related fields. In the MetaTitle field put the name of your custom field and save.

    Also, from the docs:

    If you leave MetaTitle field empty, Sitefinity CMS adds takes its value from the Title field of the static content item or from the identifier field of a dynamic content item. Otherwise, the tag is populated with the contents of the field that you have entered in MetaTitle field.

    More details here: https://docs.sitefinity.com/configure-meta-title-and-meta-description-on-widget-level

    Sitefinity 10.1 and below:

    Check this article

    Basically, in your view you get a reference to the Page object and then update its Header with the meta data you need.