#5 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(...)
.
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>
#5 Reuse a function library CreateInstance
@inherits Custom.Hybrid.Razor14
<!-- 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 -->
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;
}
}