kenticokentico-mvckentico-12

Kentico MVC culture two letter code in URL pattern


I'm trying to create a more friendly page URL in Kentico with the two letter culture code (en) instead of the full culture code (en-US). I modified the page URL pattern as seen in the image below. Is there a better way of doing this, should I create a custom macro expression?

The other thing I wanted to achieve was having the default culture not in the URL. Maybe I could also use the custom macro expression for it.

Current situation


Solution

  • I have solved the problem with a custom macro expression. This is used in the URL pattern in combination with the DocumentCulture. The macro expression takes the culture alias name which is in case of the default culture empty and else the two letter code, and returns this with a '/'.

    The url pattern for a page:

    {%Util.GetUrlCultureCode(DocumentCulture)%}{%NodeAliasPath%}
    

    The macro expression I wrote for fixing this problem is as below.

    public class CustomCultureMacroExpression : MacroMethodContainer
    {
        [MacroMethod(typeof(List<string>), "Returns the url culture code of current document", 1)]
        [MacroMethodParam(0, "Culture", typeof(string), "Current culture.")]
        public static object GetUrlCultureCode(EvaluationContext context, params object[] parameters)
        {
            // Branches according to the number of the method's parameters
            switch (parameters.Length)
            {
                case 1:
                    return GetCultureAliasOfCulture(parameters[0].ToString());
                case 2:
                    // Weird bug causing macro expression in url pattern to have two parameters where the first parameter is null.
                    return GetCultureAliasOfCulture(parameters[1].ToString());
                default:
                    // No other overloads are supported
                    return string.Empty;
            }
        }
    
        private static string GetCultureAliasOfCulture(string cultureCode)
        {
            var culture = CultureInfoProvider.GetCultureInfo(cultureCode);
            var culturealias = culture?.CultureAlias ?? string.Empty;
    
            return string.IsNullOrEmpty(culturealias) ? string.Empty : $"/{culturealias}";
        }
    }