I'm experimenting with Blazor for WebAssembly, and am looking for help with achieving something I found simple in basic JavaScript/HTML.
If I have a code section in an HTML page, in a script tag, I can easily show that section of code in my HTML view by setting the innerHTML of some element, say a div, to the innerHTML of that script tag. Like:
<div id="content" onload="fillDivWithCode()"></div>
<script id="code"> function foo() { return "bar"; } </script>
<script>
fillDivWithCode() {
var div = document.getElementById("content");
var codeScript = document.getElementById("code");
div.innerHTML = codeScript.innerHTML;
// now the entire contents of the "code" script will be shown in the DOM
}
</script>
However, say I want to do something similar in Blazor; how can I do it? For example, say my Razor page looks like
@page "/"
<div id="content"></div>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
I want to display inside the "content" div the entire code in the @code section -- can this be done? If so, how?
Well,.. depending on how bad you want this, there are a few options that come to mind.
In a variety of ways you can have an automated task that processes your *.razor files, finds and extracts your @code blocks, and puts that content somewhere.
Maybe write it back into the page within a <code>
block or save it to a resource or markdown file.
The trick is to get this happen automatically as part of build, commit, or deploy.
Here are some options:
Sounds complicated?
Not really. I whipped up a dotnet CLI command that does exactly this:
https://github.com/mehalick/BlazorCodeExtractor
If you start with a simple Index.razor page:
<h1>Hello World!</h1>
@code {
private string _name = "Andy";
}
Just run extract-blazor-code
from the command line (or as a build task) and you end up with an Index.razor.md file alongside your original file containing only your original @code block.
```
@code {
private string _name = "Andy";
}
```
Now you can use show that file within any new or existing page.
Alternatively, and my first take, you can save the content directly into a <code>
block in the original razor page instead of a separate markdown file. A version of this is a few commits back in the repo linked above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.