Page Metadata - Use macro to dynamically insert value of page fields

Albert Zaballero asked on April 26, 2022 21:26

We use Kentico 12 (MVC) and have a requirement to autopopulate/pre-populate metadata title and description fields automatically from fields we defined in a page type we recently created. The documentation here states macro expressions can be used to dynamically insert values from fields:

Use macro expressions in format {%FieldName%} to dynamically insert values of page fields into metadata values.

I'm new to Kentico development and learning how macros work. Does anyone have more info. on how or where to apply the macro in that statement? This page has an example of how to implement a macro expression in an MVC application:

Is this the approach the previous document is talking about? If yes, and then this would apply to the front-end MVC app. But, can this be done to the backend Kentico CMS (Page > Properties > Metadata) fields themselves? Can the Kentico CMS itself be customized to pre-populate the metadata fields in the backend? Or, is it a bad idea to edit the CMS source code?

using CMS.MacroEngine;


// Resolves macros in the specified string using a new instance of the global resolver
string resolvedTextGlobal = MacroResolver.Resolve("The current user is: {% CurrentUser.UserName %}");

Recent Answers

Juraj Ondrus answered on April 27, 2022 07:05

First of all I would recommend checking whether the documentation you are using is for MVC or portal engine development mode or for both: sample screen shot. So, you are referring to a documentation page which is related to portal engine model and not MVC.

Anyway, imagine you have a page type which has a field named "ArticleTitle". So, the macro format {%FieldName%} means that the macro to get the value of that title field will be {%ArticleTitle%}.

In MVC development model, the macro works only in Page title metadate field. Other fields do not have macro support. However, it does not make much sense to use macros here - because in your MVC code you need to call API to resolve macro -> macro calls another API to get the actual field value. So, there are two additional code executions while in your MVC code you can use the API directly to get the value from the page field you want and pass it to the view.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.