Why won't Razor parse this in html mode? - asp.net-mvc

I'm making a reusable package and in order to get the client side to work both with straight javascript and module loaders I have a code paths that requires me to document.write out script tags.
In my razor view I have something like this:
<script>
...
document.write([
'<script type="text/javascript" src="~/Oaf/SlimHeader/Media/Scripts/jquery-1.9.1.min.js"></script>',
'<script type="text/javascript" src="~/Oaf/SlimHeader/Media/Scripts/jquery-migrate-1.2.1.min.js"></script>',
].join('\n'))
...
</script>
Which Razor refuses to interpret in html mode:
Parser Error Message: Unterminated string literal. Strings that start
with a quotation mark (") must be terminated before the end of the
line. However, strings that start with # and a quotation mark (#")
can span multiple lines.
indicating the error is in the first script tag. This is javascript, I don't want Razor involved at all! (Ok, it would be nice if it parsed the ~ but honestly I can take care of that myself).
I've tried prefixing every line with #: and surrounding the whole thing in #" ... "# but neither seems to work.

This is not a razor issue, this code is invalid even in a simple HTML file, and will cause problems in the browser.
The solution is to:
var a = '<script><' +' /script>';
The bug has been closed as by design.

Thanks to Aron who got me to pare this down thereby prompting me to discover the answer.
Pared down the broken code looked like this (I hadn't included the if in the question):
#if (true) {
<script type="text/javascript">
var a = '<script></script>';
</script>
}
something in the interplay between the #if and the <script> tag in a sting just does not sit well. If I force text mode on each line inside the if by prefixing with #: then it works.
In the original question the solution it to prefix every line inside the Razor block with #:. Surrounding in a <text> block will not work. If you don't prefix every line with #: then you will get a parsing error very possibly for a line that was prefixed.
Seems like a bug with Razor. Will report it.

Related

Carrying style IDs/names from HTML to .docx?

Is it possible to somehow tell pandoc to carry the names of styles from original HTML to .docx?
I understand that in order to tune the actual styles, I should be using reference.docx file generated by pandoc. However, reference.docx is limited to what styles it has to: headings, body text, block text, etc.
I'd like to:
specify "myStyle" style in the input HTML (via a "class" attribute, via any other HTML attribute or even via a filter code written in Lua),
<html>
<body>
<p>Hello</p>
<p class="myStyle">World!</p>
</body>
</html>
add a custom "myStyle" to reference.docx using Word,
run a html->docx conversion an expect pandoc generate a paragraph element with "myStyle" (instead of BodyText, which I believe it sets by default), so the end result looks like this (contents of word/document.xml inside the resulting output.docx was cut for brevity):
<w:p>
<w:pPr>
<w:pStyle w:val="BodyText" />
</w:pPr>
<w:r>
<w:txml:space="preserve">Hello</w:t>
</w:r>
</w:p>
<w:p>
<w:pPr>
<w:pStyle w:val="myStyle" />
</w:pPr>
<w:r>
<w:txml:space="preserve">World!</w:t>
</w:r>
</w:p>
There's some evidence styleId can be passed around, but I don't really understand it and am unable to find any documentation about it.
Doc on filtering in Lua states you can access attrs when manipulating a pandoc.div, but it says nothing about whether any of the attrs will be interpreted by pandoc in any meaningful way.
Finally, found what I needed – Custom styles. It's limited, but better than what I arrived earlier, and of course much better than nothing at all :)
I'll leave a step-by-step guide here in case anyone stumbles upon a similar question.
First, generate a reference.docx file like this:
pandoc --print-default-data-file reference.docx > styles.docx
Then open the file in MS Word (I was using a macOS version) you'll see this:
Click the "New style..." button on the right, and create a style to your liking. In my case I made change the style of text to be bold, in blue color:
Since I am converting from HTML to DOCX, here's my input.html:
<html>
<body>
<div>Page 1</div>
<div custom-style="eugene-is-testing">Page 2</div>
<div>Page 3</div>
</body>
</html>
Run:
pandoc --standalone --reference-doc styles.docx --output output.docx input.html
Finally, enjoy the result:

Trouble rendering some latex syntax in MathJax with Jekyll on github pages

I found that some of latex syntaxes are not rendered with MathJax with Jekyll in my git page.
For example, in this post
this line:
$z = \overbrace{\underbrace{x}\text{real} +\underbrace{iy}\text{imaginary}}^\text{complex number}$
should look like this
Some other latex syntax works well, like this
What should I add to solve this problem? I guess MathJax is not loading the required library (e.g. \usepackage{amsmath} in the above case).
The code of the page is here.
The following code shows the my configuration of matjax.
<script type="text/x-mathjax-config"> MathJax.Hub.Config({ TeX: { equationNumbers: { autoNumber: "all" } } }); </script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
}
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript"></script>
Note that in Jekyll's Markdown syntax, underlines are used to indicate italic text, so Jekyll is inserting <em> tags around \text{real} +\underbrace{iy} where the underscores were (notice that the underscores are missing in the output and that the text is in italics). MathJax can't process math that contains HTML tags, so this math equation is skipped.
You need to make sure that Markdown doesn't interfere with your TeX notation. That can be done in several ways. You could use \_ instead of _ in order to prevent the underscores from being interpreted as italics. Alternatively, you could use <span>...</span> around inline math and <div>...</div> around display math, as suggested here.
Just a hunch but looking at the code posted within your question, I think it might be better to keep all the MathJax related stuff within the <script> tags. I write this because I've yet to find the need to wrap anything in a <span>.
Here's what my _includes/mathjax.html file looks like by piecing together two blocks from the docs...
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\(','\\)']],
processEscapes: true
}
});
</script>
... and this is how I include it...
---
layout: post
title: Some of Thing
---
{%- include mathjax.html -%}
Notes about $ \sum_{Thing} $
Note how the configs are within the same <script> tag as what is doing the sourcing (src="<url-or-path>"),
For completeness a post source to go with rendered post, which uses the $$ way of doing multi-line formatting within the first thirty lines of the source, and then the $ in line way of doing things just after the first code formatted block (within the notes) of the rendered version.
And (for bonus points I suppose), what I think the corrected code might look like from the question.
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript">
MathJax.Hub.Config({ TeX: { equationNumbers: { autoNumber: "all" } } });
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
}
});
</script>
One other note worthy thing that I found my tests is that the \( ... \sum_{Thing} ... \), in-line syntax did not trigger whatever pre-parser Jekyll's using to add html tags to such things; in other-words I had to use the $ ... \sum_{Thing} ... $ syntax even before adding any configs for MathJax's srcing.
For those that got this far but wanted to cut-down on the CDN usage for some reason, ya may instead be interested in the other answer that I've posted on getting MathJax and Jekyll to play-nice.
And for those that want some Liquid to JavaScript configuration translation liquid-utilities/includes-mathjax is now available; allows for configuring MathJax via _config.yml and individual post/page FrontMatter.

Fixing "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

I've included two below scripts in my header and I get the error "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js key=************"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
When I remove either script, I get additional js errors. How can I properly refactor these two scripts in my rails app?
In your example above, you're including the same script twice, but with different parameters. You should be able to solve your issue by including the script once, with all the required parameters like this:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&libraries=places&sensor=false"></script>
If you're calling google maps via an ajax call, you can use window.google = {} upon exiting the state in which the map was called.
I know that in my case it's not a Rails app but might help to someone else ... I'm working with React and I was getting the same error when I was switching between views/pages.
And like wLc said window.google = {} worked like a charm and was deleting the error in the console but the <script> tag was remaining in the html and was added every time I was revisiting the page that has the map.
On componentWillUnmount I've added some code to remove the tag.
const allScripts = document.getElementsByTagName( 'script' );
[].filter.call(
allScripts,
( scpt ) => scpt.src.indexOf( 'key=googleAPIKEY' ) >= 0
)[ 0 ].remove();
window.google = {};

xpath with contains throws error if string starts with a number

I'm running into a strange problem with nokogiri and xpath. I want to parse a HTML document and get all links by href value and the anchor text they contain.
Here's my xpath so far:
xpath = "//a[contains(text(), #{link['anchor_text']}) and #href='#{link['target_url']}']"
a = doc.search(xpath)
This works fine so far as long as link['anchor_text'] is a string without numbers.
If I'm trying to get a link with the anchor text "11example" it throws the following error:
Invalid expression: //a[contains(text(), 11example) and #href='http://www.example.com/']
Maybe it's just a stupid mistake, but I'm not seeing why this error occurs. If I put some quotes around the #{link['anchor_text']} in the xpath, nothing is working.
Edit: Here's the sample HTML:
<!DOCTYPE html>
<head>
<title>Example.com</title>
</head>
<body>
<p>
<strong>Here is some text</strong><br />
11exampleSome text here and there
</p>
<p>
<strong>Another text</strong><br />
example.comSome text here and there
</p>
</body>
Edit2: If I run these queries manually in irb console everything works as expected, but only if I put the text in quotes.
Thanks in advance!
Kind regards,
madhippie
The simple answer is that you are missing quotes around #{link['anchor_text']}, like you have around #{link['target_url']}. The full XPath should be
xpath = "//a[contains(text(), '#{link['anchor_text']}') and #href='#{link['target_url']}']"
The reason it appears to work (at least not produce an error) when you don’t start with a number is that the string is being interpreted as a node query. For example Nokogiri is looking for a tag named <example.com> inside the <a> tag, then converting it to a string and seeing if the text nodes of the <a> tag contain that string. If the tag isn’t there (as in this case) then the result of contains is always true.
As a demonstration, with the HTML:
<q>foo</q>example
<q>foo</q>foo
foo
Then the query
doc.search("//a[contains(text(), q)]")
doesn’t match the first <a> tag, but does match the second and third.
When the string starts with a number, it can’t be parsed into a node query since names starting with digits aren’t valid XML (or HTML) element names, so you get an error.

Genshi if else statement

I have been try ot get genshi py:if to work with python expression.
To make things simple I try the following code.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/">
<body>
<py:if test = ${len(linstoflinks)>0}>
<p>List has lenght</p>
</py:if>
</body>
</html>
In the Genshi docs they say I can put any python expressions
as long I put my expression in curly braces with a dollar sign in front.
http://genshi.edgewall.org/wiki/GenshiTutorial.
I even try
<py:if test = "${True}">
<py:if test = "${1==1}">
This simple code does not work. error is : not well formed (invalid token)
This works
<py:if test = "foo">
Anyone has any idea how I can make this if statement work with python expression.
Thanks
You don't need curly braces inside template directives.
try this
<py:if test="len(linstoflinks)>0">

Resources