javascript code in HTML file below
<script th:inline="javascript">
.
.
.
for (var i = 0, l = 100; i < l; i++) {
list.push($.extend({}, sampleData[(Math.floor(Math.random() *
sampleData.length))]));
}
thymeleaf error message is that
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Could
not parse as expression: "Math.floor(Math.random() *
sampleData.length)" (template: "gridTest" - line 165, col 63)
how do I resolve this ?
thanks.
The text [(...)] is a variation on JavaScript inlining -- which is why Thymeleaf is trying to parse [(Math.floor(Math.random() * sampleData.length))] as a Thymeleaf expression (and consequently throwing the error).
In any case, the parenthesis around the Math.floor(...) expression are unneeded, so you can remove them and the Thymeleaf will work.
<script th:inline="javascript">
.
.
.
for (var i = 0, l = 100; i < l; i++) {
list.push($.extend({}, sampleData[Math.floor(Math.random() * sampleData.length)]));
}
</script>
Related
I know that #: is for output a single line of content containing plain text or unmatched HTML tags;
If so , why do I get an error for :
( ":" is not valid at the start of a code block. Only identifiers, keywords, comments, "(" and "{" are valid.)
#foreach (int line in new int[] { 0, 1 })
{
<span>
#: aaaaa
</span>
}
While this run as expected :
#foreach (int line in new int[] { 0, 1 })
{
#: aaaaa
}
#: is used to mix text within a code block.
When you use the span tag or any other html elements, inside a C# code block, you are already mixing HTML tag and razor can properly parse and execute it. When you use #: inside an HTML element (non-code block), it is not even valid.
In short, you can use HTML elements inside a code block as wrapper to mix plaintext/html.
#foreach (int line in new int[] { 0, 1 })
{
<div>Hello</div>
}
In razor, the #: tag produce the same result as the text tag when it comes to mixing plain text within a code block. The below will also produce same result as your second code block.
#foreach (int line in new int[] { 0, 1 })
{
<text>aaa533</text>
}
I am using katex to render math.
https://github.com/Khan/KaTeX
Generally, to get this to work I link to the files katex.min.js and katex.min.css from a cdn, which is one of the ways the directions suggest.
I wrap what needs to be rendered in tags and give all the same class. For example:
<span class='math'>\begin{bmatrix}a & b \\c & d\end{bmatrix}</span>
And inside a script tag I apply the following:
var math = document.getElementsByClassName('math');
for (var i = 0; i < math.length; i++) {
katex.render(math[i].innerHTML, math[i]);
}
So, my implementation works but there is a problem in what katex returns. The output of the above gives me:
This exact same question is asked here:
https://github.com/j13z/reveal.js-math-katex-plugin/issues/2
But I can't understand any of it.
The solution is to use element.textContent, not element.innerHTML.
If I use a form like what follows, the matrix will be rendered properly.
var math = document.getElementsByClassName('math');
for (var i = 0; i < math.length; i++) {
katex.render(math[i].textContent, math[i]); // <--element.textContent
}
A solution that works for me is the following (it is more of a hack rather than a fix):
<script type="text/javascript">
//first we define a function
function replaceAmp(str,replaceWhat,replaceTo){
replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
//next we use this function to replace all occurences of 'amp;' with ""
var katexText = $(this).html();
var html = katex.renderToString(String.raw``+katexText+``, {
throwOnError: false
});
//hack to fix amp; error
var amp = '<span class="mord mathdefault">a</span><span class="mord mathdefault">m</span><span class="mord mathdefault">p</span><span class="mpunct">;</span>';
var html = replaceAmp(html, amp, "");
</script>
function convert(input) {
var input = input.replace(/amp;/g, '&'); //Find all 'amp;' and replace with '&'
input=input.replace(/&&/g, '&'); //Find all '&&' and replace with '&'. For leveling 10&x+ &3&y+&125&z = 34232
var html = katex.renderToString(input, {
throwOnError: false});
return html
}
Which version are you using?
Edit the src/utils.js and comment line number 51 to 55 after updated run in terminal npm run build command.
I have a method that fills up the elements of an int[,]. The elements that need to be filled are stored in a .txt file like this:
1
1
2
2
Meaning that I have to fill up the [1,1] and [2,2] element.
For this I use this but it gives the error above
int x = 0;
int y = 0;
for (int i = 0; i < 2; i++)
{
x = int.Parse(SR.ReadLine());
y = int.Parse(SR.ReadLine());
mezo.mezo[x, y] = 1;
}
Thanks in advance!
According to MSDN(http://msdn.microsoft.com/en-IN/library/b3h1hf19.aspx) a FormatException is thrown when:
s is not in the correct format.
s in your case is SR.ReadLine() which is returning some value that is not recognized as a number format.
At first look it might be because of whitespaces in your file.
Try
SR.ReadLine().Trim()
OR
NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite for the number style in the Parse method.
I'm new to .net MVC and Razor engine but I have been using PHP for a long time. I'm trying to do this PHP code in Razor:
var data = [
<?php for ($i = 0; $i < 50; ++$i) {
echo '[' . $i . ',' . sin($i) . ']';
if ($i != 49)
echo ',';
?>
],
I managed to do it using this, but it looks bad and complex for something so simple
var data = [
#for(int i = 0; i < 50; ++i) {
<text>[</text>#i<text>,</text>#Math.Sin(i)<text>]</text>if (i != 49) {<text>,</text>}
}
];
The problem is that [, ] and , are confused with Razor syntax and gives syntax errors, so I had to wrap them on <text> tags.
Is there a simpler/nicer way to do this? Maybe something like the PHP echo.
Thanks.
A gerenal equivalent of echo in MVC cshtml might be:
#Html.Raw("SomeStringDirectlyInsideTheBrowserPageHTMLCode")
This renders the (dynamic) string at its position where '<' and '>' no need to be HTML-coded. For example #Html.Raw(String.Format("<div class=\"{0}\" style=\"{1}\">", myclass, mystyle)) works fine.
Note that the HTML tags rendered by #Html.Raw(MyString) cannot be checked by the compiler. I mean: #Html.Raw("<div ....>") cannot be closed by mere </div> because you will get an error (<div ....> is not detected by the compiler) so you must close the tag with #Html.Raw("</div>")
P.S.In some cases this doesn't work (for example it fails within DevExpress) - use ViewContext.Writer.Write() or ViewContext.Writer.WriteLine() instead.
Use this:
#String.Format("[{0},{1}]", i, Math.Sin(i))
And for comma you can use String.Join() if you create array (String.Join Method )
Old question I know, but an alternative is to use the plaintext syntax #:
var data = [
#for (int i = 0; i < 50; ++i)
{
#:[#i,#Math.Sin(i)]
#(i != 49 ? "," : "")
}
];
Constructing a JSON object using a view is not really the best way to go about it. You can use the native JSON support to do this directly from a controller, for example:
public JsonResult SinArray()
{
return new JsonResult() {
Data = Enumerable.Range(0, 50).Select(i => new[] { i, Math.Sin(i) }),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
This returns
[[0,0],[1,0.8414709848078965],[2,0.90929742682568171],.....,[49,-0.95375265275947185]]
As a bonus you get the correct content-type.
First, I know, there already is a Markdown parser for PHP.
I also took a look to this question but it doesn't answer to my question.
Obviously, even if the title mention PHP, if it's language agnostic, because I'd like to know what are the step I've to go through to do that.
I've read about PEG, but I've to admit, I didn't really understand the example provided with the PHP parser.
I've also read about CFG.
I've found Zend_Markup_Parser_Textile which seems to construct a so called "Token Tree" (what's about it?) but it currently unusable. (Btw, Textile is not Markdown)
So, concretely, how would you go to this?
Obviously I though about using Regex but, I'm afraid.
Because Markdown supports several syntaxes for the same element (Setext and atx).
Could you give some starting point?
You should have a look at Parsedown.
It parses Markdown text the way people do. First, it divides texts into lines. Then it looks at how these lines start and relate to each other. Finally, it looks for special characters to identify inline elements.
There is PHP Markdown Extra that seems to be popular, you could start by looking at its source.
Also, there is an object-oriented implementation of Markdown which is faster: markdown-oo-php
Ciconia - A New Markdown Parser for PHP is a good one I found.
You just need 3 things to do :
1.Install Ciconia and parse file according to the document.
2. Add corresponding css theme to make it nice, like github markdown style or here.
3. Add syntax highlighting javascript, like google Javascript code prettifier.
Then everything will look pretty good.
If you want a complete example, here is my working demo for github style markdown:
<?php
header("Content-Type: text/html;charset=utf-8");
require 'vendor/autoload.php';
use Ciconia\Ciconia;
use Ciconia\Extension\Gfm;
$ciconia = new Ciconia();
$ciconia->addExtension(new Gfm\FencedCodeBlockExtension());
$ciconia->addExtension(new Gfm\TaskListExtension());
$ciconia->addExtension(new Gfm\InlineStyleExtension());
$ciconia->addExtension(new Gfm\WhiteSpaceExtension());
$ciconia->addExtension(new Gfm\TableExtension());
$ciconia->addExtension(new Gfm\UrlAutoLinkExtension());
$contents = file_get_contents('Readme.md');
$html = $ciconia->render($contents);
?>
<!DOCTYPE html>
<html>
<head>
<title>Excel to Lua table - Readme</title>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
<link rel="stylesheet" href="./github-markdown.css">
<style>
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
}
</style>
</head>
<body>
<article class="markdown-body">
<?php
# Put HTML content in the document
echo $html;
?>
</article>
</body>
</html>
Using regexes.
<?php
/**
* Slimdown - A very basic regex-based Markdown parser. Supports the
* following elements (and can be extended via Slimdown::add_rule()):
*
* - Headers
* - Links
* - Bold
* - Emphasis
* - Deletions
* - Quotes
* - Inline code
* - Blockquotes
* - Ordered/unordered lists
* - Horizontal rules
*
* Author: Johnny Broadway <johnny#johnnybroadway.com>
* Website: https://gist.github.com/jbroadway/2836900
* License: MIT
*/
class Slimdown {
public static $rules = array (
'/(#+)(.*)/' => 'self::header', // headers
'/\[([^\[]+)\]\(([^\)]+)\)/' => '<a href=\'\2\'>\1</a>', // links
'/(\*\*|__)(.*?)\1/' => '<strong>\2</strong>', // bold
'/(\*|_)(.*?)\1/' => '<em>\2</em>', // emphasis
'/\~\~(.*?)\~\~/' => '<del>\1</del>', // del
'/\:\"(.*?)\"\:/' => '<q>\1</q>', // quote
'/`(.*?)`/' => '<code>\1</code>', // inline code
'/\n\*(.*)/' => 'self::ul_list', // ul lists
'/\n[0-9]+\.(.*)/' => 'self::ol_list', // ol lists
'/\n(>|\>)(.*)/' => 'self::blockquote ', // blockquotes
'/\n-{5,}/' => "\n<hr />", // horizontal rule
'/\n([^\n]+)\n/' => 'self::para', // add paragraphs
'/<\/ul>\s?<ul>/' => '', // fix extra ul
'/<\/ol>\s?<ol>/' => '', // fix extra ol
'/<\/blockquote><blockquote>/' => "\n" // fix extra blockquote
);
private static function para ($regs) {
$line = $regs[1];
$trimmed = trim ($line);
if (preg_match ('/^<\/?(ul|ol|li|h|p|bl)/', $trimmed)) {
return "\n" . $line . "\n";
}
return sprintf ("\n<p>%s</p>\n", $trimmed);
}
private static function ul_list ($regs) {
$item = $regs[1];
return sprintf ("\n<ul>\n\t<li>%s</li>\n</ul>", trim ($item));
}
private static function ol_list ($regs) {
$item = $regs[1];
return sprintf ("\n<ol>\n\t<li>%s</li>\n</ol>", trim ($item));
}
private static function blockquote ($regs) {
$item = $regs[2];
return sprintf ("\n<blockquote>%s</blockquote>", trim ($item));
}
private static function header ($regs) {
list ($tmp, $chars, $header) = $regs;
$level = strlen ($chars);
return sprintf ('<h%d>%s</h%d>', $level, trim ($header), $level);
}
/**
* Add a rule.
*/
public static function add_rule ($regex, $replacement) {
self::$rules[$regex] = $replacement;
}
/**
* Render some Markdown into HTML.
*/
public static function render ($text) {
$text = "\n" . $text . "\n";
foreach (self::$rules as $regex => $replacement) {
if (is_callable ( $replacement)) {
$text = preg_replace_callback ($regex, $replacement, $text);
} else {
$text = preg_replace ($regex, $replacement, $text);
}
}
return trim ($text);
}
}
echo Slimdown::render ("# Title
And *now* [a link](http://www.google.com) to **follow** and [another](http://yahoo.com/).
* One
* Two
* Three
## Subhead
One **two** three **four** five.
One __two__ three _four_ five __six__ seven _eight_.
1. One
2. Two
3. Three
More text with `inline($code)` sample.
> A block quote
> across two lines.
More text...");
Origin https://gist.github.com/jbroadway/2836900