Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Kristian 1 post 21 karma points
    Jul 30, 2013 @ 11:09
    Kristian
    0

    Access Razor variable in Content

    Hi

    Is it possible to access a Razor variable in content?

    If one of our editors are writing content and would like to use the our brand name, is there a feature in Umbraco which allows the editor to write a variable in the text?
    Example:
    Welcome to [brandName]!
    ..should render the following text to visitors:
    Welcome to My Company!
    I've been searching for answers with Google and here on the forum without any luck.
    Any suggestions would be greatly appreciated :)
  • Jeroen Breuer 4908 posts 12265 karma points MVP 5x admin c-trib
    Jul 30, 2013 @ 12:43
    Jeroen Breuer
    0

    If you render your content in Razor you could do something like this:

    The old Razor macro:

    @Model.bodyText.Replace("[brandName]", Model.Name)

    MVC Razor:

    @Model.Content.GetPropertyValue<string>("bodyText").Replace("[brandName]", Model.Name)

    Jeroen

  • Mike Chambers 636 posts 1253 karma points c-trib
    Jul 31, 2013 @ 18:01
    Mike Chambers
    0

    for one off replacements great.. but you could extend to use the umbraco dictionary for content replacements?

    something like

    try
        {
            Regex regDictionaryItem = new Regex(@"{#([^}]*)}", RegexOptions.IgnoreCase);
            MatchCollection ms = regDictionaryItem.Matches(umbraco.library.StripHtml(doc.InnerXml));
    
            foreach (Match match in ms)
            {
    
                try
                {
                    // make replacements in the content xml text nodes only, for any matching definition term
    
                    doc.DocumentElement.SetAttribute("searchAttribute0", match.Groups[0].Value);
                    XmlNodeList textNodes = doc.SelectNodes("//text() [contains(.,//@searchAttribute0)]");
    
                    for (var i = 0; i < textNodes.Count; i++)
                    {
                        //loop throught the matched textnodes to replace on a word matching basis
                        textNodes[i].InnerText = textNodes[i].InnerText.Replace(match.Groups[0].Value, umbraco.library.GetDictionaryItem(match.Groups[1].Value));
                    }
                }
                catch
                {
                    //UmbracoJPT.Utils.Files.WriteToLogFile("error", @"DICTIONARYITEM ERROR" + match.Groups[0].Value + @"
    ", true); } } } catch { }
Please Sign in or register to post replies

Write your reply to:

Draft