#6 Reuse a function library CreateInstance
Resources
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!
#6 Reuse a function library CreateInstance
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.RazorTyped @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 --> @{ // Use GetCode in RazorPro var lib = GetCode("SharedFunctions.cs"); } <div>Hello from lib: @lib.SayHello()</div> <div> <img loading="lazy" src='@lib.QrPath("https://2sxc.org")' width="75px"> </div> @* Snippet for the old v14 code, which shouldn't run but should be shown. This is a bit of a hack, but it works @{ // Use CreateInstance in Razor12 and Razor14 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 })