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(...).

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 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.Razor12
<!-- unimportant stuff, hidden -->

Reuse functions When you need a function... <!-- unimportant stuff, hidden -->

<hr>
<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>



<!-- unimportant stuff, hidden -->

Source Code of SharedFunctions.cs

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

public class SharedFunctions: Custom.Hybrid.Code12 {

  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;
    }

}