Skip to main content
Home  › ... Razor

Reuse Templates and Code Tutorials

Tutorial HomeReuse

Reuse functions

When you need a function in many places, it's best to put it into an own cshtml file and access it using CreateInstance.

Using shared library of functions

The example takes a cshtml file with a QrPath function returning the url to a qr-code. It then accesses it using CreateInstance(...).

Output

Hello from lib: Hello!
@{
  var lib = CreateInstance("SharedFunctions.cs");
}
<div>Hello from lib: @lib.SayHello()</div>
<div>
  <img loading="lazy" src='@lib.QrPath("https://2sxc.org")' width="75px">
</div>

Source Code of SharedFunctions.cs

public class SharedFunctions: Custom.Hybrid.Code14 {

  public string SayHello() {
    return "Hello!";
  }

  public string QrPath(string link) {
        // path to qr-code generator
        var qrPath = "//api.qrserver.com/v1/create-qr-code/?color={foreground}&bgcolor={background}&qzone=0&margin=0&size={dim}x{dim}&ecc={ecc}&data={link}"
            .Replace("{foreground}", App.Settings.QrForegroundColor.Replace("#", ""))
            .Replace("{background}", App.Settings.QrBackgroundColor.Replace("#", ""))
            .Replace("{dim}", App.Settings.QrDimension.ToString())
            .Replace("{ecc}", App.Settings.QrEcc)
            .Replace("{link}", link)
            ;
        return qrPath;
    }

}

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@inherits Custom.Hybrid.Razor14
@using ToSic.Razor.Blade;
<!-- unimportant stuff, hidden -->


<div @Sys.PageParts.InfoWrapper()>
  @Html.Partial("../shared/DefaultInfoSection.cshtml")
  <div @Sys.PageParts.InfoIntro()>
      <h2>Reuse functions</h2>
      <p>
        When you need a function in many places, it's best to put it into an own <code>cshtml</code> file and access it using <code>CreateInstance</code>. 
      </p>
    </div>
  </div>


<h2>Using shared library of functions</h2>
The example takes a cshtml file with a... <!-- unimportant stuff, hidden -->

  @{
    var lib = CreateInstance("SharedFunctions.cs");
  }
  <div>Hello from lib: @lib.SayHello()</div>
  <div>
    <img loading="lazy" src='@lib.QrPath("https://2sxc.org")' width="75px">
  </div>



@* Footer *@
@Html.Partial("../Shared/Layout/FooterWithSource.cshtml", new { Sys = Sys })