Developer forum

Forum » CMS - Standard features » A general question about cache´ing Razor templates

A general question about cache´ing Razor templates

Hans Ravnsfjall
Hans Ravnsfjall
Reply

This is a general question about cache´ing (which i know very little about, so please be gentle if my questions is stupid, and feel free to come with suggestions of alternatives)

I don´t know if this is possible in a regular razor template and/or if it´s needed - or if it´s alternatively already taken care of, when the template is parsed.

 

But what I want ask is, if there is a way to cache some of the values created in razor template, since I don´t want them to tax the server everytime a page is requested. Below is an example of some string handling, that does not have to repeat itself every time this page is loaded.

@{
string readText = File.ReadAllText(htmlpage); // Read the entire contents of the htmlfile
var substringlength = readText.LastIndexOf("<div class=\"startInclude\"></div>") - readText.IndexOf("<div class=\"endInclude\"></div>");
string content = readText.Substring(readText.IndexOf("<div class=\"startInclude\"></div>"), @substringlength).ToString();
}

Is there a way that I can tell the program to cache the value of the string content and avoid going through the  process leading to it´s value everytime? If so, any guidance on how i can do this?

 

/Hans


Replies

 
Nicolai Pedersen
Reply
This post has been marked as an answer

Hi Hans

You can use Dynamicweb.Caching:

if (Cache.Current.Contains("MyCacheky"))
            {
                string value;
                if (Cache.Current.TryGet<string>("MyCacheky", out value))
                {
                    //value now contains the content from the cache
                }

            }
            else
            {
                //The cache did not exist, so read file here and put it in cache "very long string"
                Cache.Current.Set("MyCacheky", "Very long string");
            }

By default it uses memory cache that holds on to the data for 10 minutes. The Set method on the cache also takes a third parameter that is a cachin policy if you need another policy.

BR Nicolai

Votes for this answer: 1
 
Hans Ravnsfjall
Hans Ravnsfjall
Reply

Perfect Nicolai, thank you 👍🏻

/Hans

 

You must be logged in to post in the forum