#6 Reuse a function library CreateInstance
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;
}
}
#6 Reuse a function library CreateInstance
@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 })