Generate HTML file with both quote ' and " from R - html

I need to create an HTML file from R software. The problem is that javascript implies simple quote and styles double quote in the string generated.
cat() function returns a quite good text removing backslashs in front of ". But I did not found how to print it like this in an html file using write.table(Text, "index.html", sep="\t")
Thanks in advance for any help.
NB : I removed a "<" character in front of /script in order to be able to post it =)
For exemple :
Text=paste0('<html>
<script type="text/javascript">',
"function lang1(event) {
var iframe = document.getElementById('id1');
var target = event.target || event.srcElement;
iframe.src = event.target.innerHTML + '.html';
}
/script>",
'<body style="overflow:hidden; margin:0">
<div id="main">
<div id="content">
<table style="border: 0; height:100%;width:100%;">
<tr style="height:5%;">
<td colspan="2" style="text-align:center;">
<h2>',paste0("some text"),'</h2>
</td>
</tr>
<tr>
<td style="width: 10%;font-size:14px;">
<ul onclick="lang1(event);">',
paste('<li>',c("link1","link2"),'</li>',collapse=""),
'</ul>
</td>
<td style="width: 90%;">
<iframe id="id1" width="99%" height="99%"></iframe>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>')
Text=gsub("\n","",Text)

I'm not sure I fully understand the question but whenever I generate html files from text in R, I use the \ character to escape quote marks that are needed in the JavaScript.
Then I open a file connection and use the writeLines function to correctly write my text to the file
Text<-"<!doctype html>
<html lang=\"en\">
<head>
<meta charset=\"utf-8\">
<style>
body {
font-size : 16px;
font-family: \"Helvetica Neue\",Helvetica,Arial,sans-serif;
}
</style>
</head>
</html>
"
fileConn<-file("mywebpage.html")
writeLines(Text, fileConn)
close(fileConn)
Maybe that will help you.

Related

Limit decimal numbers in html and where to put the script

So I’ve got a program that prints a html report with some numbers from within the program.
The output number includes 6 decimals, but I want to limit it to 2 decimals..
I’ve read a bunch of articles about coding it, but lacking basic understanding of this type of coding, I need help to write the code.
The code looks like this within the program:
<HTML>
<P align="center">
<img src="image.png">
</P>
<FONT face="Tahoma" size=4 color="Blue">
<P align="center">Rapport</P>
</FONT>
<FONT face="Arial" size=2 color="Black">
<P align="center"><strong>{Date} {Time}</strong></P>
<TABLE border="1" align="center">
<TR>
<TH bgcolor="lightYellow">Vatn 1</TH>
<TH bgcolor="lightYellow">Vatn 2</TH>
<TH bgcolor="lightYellow">Salt</TH>
</TR>
<TR>
<TD bgcolor="#C6DEFF">{vatn1}</TH>
<TD bgcolor="#C6DEFF">{vatn2}</TH>
<TD bgcolor="#C6DEFF">{salt}</TH>
</TR>
</TABLE>
<button onclick="myFunction()">Prenta síðuna</button>
<script>
function myFunction() {
window.print();
}
</script>
<input type="button" align="center" value="Lukka síðu" onclick="self.close()">
</FONT>
</HTML>
And after printed, ready to open in the browser:
<HTML>
<P align="center">
<img src="image.png">
</P>
<FONT face="Tahoma" size=4 color="Blue">
<P align="center">Rapport</P>
</FONT>
<FONT face="Arial" size=2 color="Black">
<P align="center"><strong>{Date} {Time}</strong></P>
<TABLE border="1" align="center">
<TR>
<TH bgcolor="lightYellow">Vatn 1</TH>
<TH bgcolor="lightYellow">Vatn 2</TH>
<TH bgcolor="lightYellow">Salt</TH>
</TR>
<TR>
<TD bgcolor="#C6DEFF">{1.000000}</TH>
<TD bgcolor="#C6DEFF">{2.000000}</TH>
<TD bgcolor="#C6DEFF">{3.000000}</TH>
</TR>
</TABLE>
<button onclick="myFunction()">Prenta síðuna</button>
<script>
function myFunction() {
window.print();
}
</script>
<input type="button" align="center" value="Lukka síðu" onclick="self.close()">
</FONT>
</HTML>
So as far as I know I need a script to process the number, what should it look like and where in my file do I place it? Also whatever tag the edited number ends up in, how do I insert it in the table?
Thanks in advance 🤓
Are you able to give any more info on the program you are using to do this, please?
At a basic level, (depending on your program) scripts can be put on a webpage in-between <script></script> tags.
Now, by looking at the <td>{number}</td> I would assume it is a template of some kind.
If it can do it, try <td>{nuumber.toFixed(2)}</td>
As it's been mentioned, using toFixed(2) on financial data can round numbers incorrectly.
Out of the scope of these question but this article explains why. (Slightly advance but linked for anyone else wondering why!)
I would suggest a better way but without knowing what you're using and the environment that would be too much assumption.
I'm not sure how the information is bound in HTML, so you can change it after the data is loaded.
you can change this block:
<script>
function myFunction() {
window.print();
}
</script>
to this one; This is not a good method but it works as a trick:
/*Important to know (1)*/
<script src="jquery-3.5.1.min.js"></script>
<script>
function myFunction() {
window.print();
}
setTimeout(() => {
$("td").each((i, e) => {
e = $(e);
let data = e.html().replace("}", "").replace("{", "");
e.html(parseFloat(data).toFixed(2));
});
}, 1000);
</script>
(1) Download JQuery and link the HTML to it.
Also if you do not want to use JQuery you can use pure javascript like this:
<script>
function myFunction() {
window.print();
}
setTimeout(() => {
let tags = document.getElementsByTagName("td");
for (let i = 0; i < tags.length; i++) {
let html = tags[i].innerHTML;
html = html.split("{").join("").split("}").join("")
tags[i].innerHTML = parseFloat(html).toFixed(2);
}
}, 1000);
</script>

How to avoid html blocks with regex

I have to find all the strings surrounded by "[" and "]" using regex, but avoiding the ones inside the <table></table> block, for example:
<html>
<body>
<p><table>
<tbody>
<tr>
<td style="border-style: solid; border-width:1px;">
<span style="font-family: Courier;">[data1]</span>
</td>
<td style="border-style: solid; border-width:1px;">
<span style="font-family: Courier;">[data10]</span>
</td>
</tr>
</tbody>
</table>
</p>
<p>[data3] [data4] [data5]</p>
</body>
</html>
in this case only [data3], [data4] and [data5] should be found.
So far I have this:
#"(((?<!<span>)(\[[a-zA-Z_0-9]+)](?!<\/span>))|((?<!<span>)(\[[a-zA-Z_0-9]+)])|((\[[a-zA-Z_0-9]+)](?!<\/span>)))(?!.*\1)"
That finds all the [] blocks that are not surrounded by tags and I tried adding a negative lookahead and lookbehind of but it doesn't work, it stills gets the ones inside the table block.
Hope you guys can help me with this.
Below regex will return your all [data] which enclose in <p> </p> tag.
/<p.*?>\[(.*?)\]<*.p>/g
so above regex will return this <p>[data3] [data4] [data5]</p> from your above HTML code.
When you get that string from above regex then use below regex to get only all [data] string.
/\[(.*?)\]/g
so above regex will return " [data3][data4][data5] " from above string.

Using a variable in the body of a HTML email as URL in a hyperlink

I have a Google script that sends out a HTML email from a spreadsheet.
One cell in the spreadsheet holds an URL that is changeable as it is composed from values of other cells.
In my GS I read this URL into a var.
Now I want to use this var in my HTML code that renders the email so that the email receiver can click on a link that opens this custom URL.
I can not find a solution to replace the fixed URL with a variable that holds my custom URL
Please check the HTML code where it says " "
that's where I'm placing a var, but doing it obviously wrong.
**** Google script*****
var CO_PP = COSheet.getRange(2,11).getValue() ;
var CO_PP_href = ("<a href=\"" + CO_PP + "\">") ; // use a backslash \ to escape the quotation marks.
var EmailBody = HtmlService.createTemplateFromFile(template);
EmailBody.EmailVar1 = CO_Name;
EmailBody.EmailVar2 = CO_Email;
EmailBody.EmailVar13 = CO_PP_href;
var MyHtmlBody = EmailBody.evaluate().getContent()
var EmailSubject = "Credits Order SUCCES .:: CADsherpa Weblink ::."
MailApp.sendEmail(CO_Email, EmailSubject, "Your emailreader does not support HTML." +
" Try opening this message with a different email reader or take contact with info#cadsherpa.com", {htmlBody: MyHtmlBody, attachments: PDF_ToSend });
*******HTML*******
<!-- button start -->
<div>
<p> </p>
<table align="left" border="0" cellpadding="1" cellspacing="1" style="height:10px;width:185px;">
<tbody>
<tr>
<td style="white-space: nowrap; text-align: center; vertical-align: middle; background-color: rgb(51, 102, 255);">
<h3> +<?= EmailVar13 ?>+ <span style="font-size:18px;"> <!-- PROBLEM ON THIS LINE -->
<strong><em><span style="font-family:arial,helvetica,sans-serif;">
<span style="color:#FFFFFF;">Pay with PayPal </span></span></em></strong></span></a></h3>
</td>
</tr>
</tbody>
</table>
<p> </p>
</div>
<!-- button end -->
When using HTML templating in GAS, the variables assigned to the template will be escaped. That means that in your case, if CO_PP_href was set to the expression "<a href=\"" + CO_PP + "\">" the actual tags will not be placed into the HTML, but rather the escaped version (<a href="...">) so that it can be treated as printable "text" within your page.
For your needs, I propose a different solution. You can firstly create the <a> tag inside the html template, and only the href attribute thereof will be set when evaluating the template. The solution would look as follows:
HTML
<!-- button start -->
<div>
<p> </p>
<table align="left" border="0" cellpadding="1" cellspacing="1" style="height:10px;width:185px;">
<tbody>
<tr>
<td style="white-space: nowrap; text-align: center; vertical-align: middle; background-color: rgb(51, 102, 255);">
<h3> <a href="<?= EmailVar13 ?>"> <span style="font-size:18px;">
<strong><em><span style="font-family:arial,helvetica,sans-serif;">
<span style="color:#FFFFFF;">Pay with PayPal </span></span></em></strong></span></a></h3>
</td>
</tr>
</tbody>
</table>
<p> </p>
</div>
<!-- button end -->
GAS
var CO_PP = COSheet.getRange(2,11).getValue() ;
var EmailBody = HtmlService.createTemplateFromFile(template);
EmailBody.EmailVar1 = CO_Name;
EmailBody.EmailVar2 = CO_Email;
EmailBody.EmailVar13 = CO_PP;
var MyHtmlBody = EmailBody.evaluate().getContent()
var EmailSubject = "Credits Order SUCCES .:: CADsherpa Weblink ::."
MailApp.sendEmail(CO_Email, EmailSubject, "Your emailreader does not support HTML." +
" Try opening this message with a different email reader or take contact with info#cadsherpa.com", {htmlBody: MyHtmlBody, attachments: PDF_ToSend });

setting div element value in html

How to set values for the below div block (setting values in '?' placeholder).
<table>
<tr>
<td class="tfArrive " valign="top">
<div class="tfArrAp" id="txt3">
? </div>
</td> </tr>
</table>
I have tried with following scenario, but not working
<script type="text/javascript">
document.getElementById('txt3').innerHTML = "TEST";
</script>
Your script is working perfectly, it's just that you need to be sure that you are placing the script after the HTML is rendered, so first you need to print the tables out and than use the script tag, because if you place the script before the id="txt3" has rendered, it won't change anything as onload the script didn't find any, so this should be the order...
<table>
<tr>
<td class="tfArrive " valign="top">
<div class="tfArrAp" id="txt3">
?
</div>
</td>
</tr>
</table>
<script type="text/javascript">
document.getElementById('txt3').innerHTML = "TEST";
</script>
Side Note : If you are using HTML5, you don't need
type="text/javascript" anymore, as now, default is JavaScript
$(document).ready(function(){
$('#txt3').html("New Text");
});
Be sure your page is loaded before you manipulate it:
<script type="text/javascript">
window.onload = function() {
document.getElementById('txt3').innerHTML = "TEST";
}
</script>

ckeditor and razor syntax templates

I have an interesting issue. I have a website which sends emails.
The email templates are often straight forward but for one client he wants me to convert content from his public website into email friendly html.
I want to not just solve the problem for his specific website but for other unknown websites.
So I remembered that you can run Razor as a template engine.
Long story short. It is working and working well.
My issue comes down to this. When someone edits the template with razor style for loops Ckeditor acts quite strangely.
Any idea how to keep CKEditor from screwing up?
<table style="width: 100%;" width="100%">
<tbody>
#foreach (var row in body.indexPageRow) {
foreach (var cell in row.teaser) {
<tr>
<td class="row">#Raw(cell.teaserContent.a.Html)</td>
<td class="row">#Raw(cell.teaserContent.div.InnerHtml)</td>
</tr>
}}
</tbody>
</table>
The above code when saved in ckeditor removes the razor information and becomes an empty table
<table style="width: 100%;" width="100%">
<tbody></tbody>
</table>
The only way I can think of to achieve this would be to use html comments in conjunction with razor comments.
Initially you would author the razor template like so:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<table>
<tbody>
<tr><td>X</td><td>Y</td></tr>
#*<!--*#
#for (var x = 1; x < 5; x++) {
for (var y = 1; y < 5; y++) {
#*-->*#
<tr>
<td class="row">#Html.Raw(x)</td>
<td class="row">#Html.Raw(y)</td>
</tr>
#*<!--*#
}
}
#*-->*#
</tbody>
</table>
</body>
</html>
The code above is valid and will render without error. But when you put it into the html editor it will be rearranged by the browser, so you will need to alter it just before it is displayed for editing so that the razor comments are removed and only the html comments remain.
So, once you have removed the razor comments by replacing all instances of #*<!--*# with <!-- and all instances of #*-->*# with --> you should have the following
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<table>
<tbody>
<tr><td>X</td><td>Y</td></tr>
<!--
#for (var x = 1; x < 5; x++) {
for (var y = 1; y < 5; y++) {
-->
<tr>
<td class="row">#Html.Raw(x)</td>
<td class="row">#Html.Raw(y)</td>
</tr>
<!--
}
}
-->
</tbody>
</table>
</body>
</html>
This will render in the html editor and wont get mangled by the browser as pointed out by Alfonso, an example of this on jsfiddle http://jsfiddle.net/wPGLd/3/
Once the editing is complete you will need to capture the html and reapply the razor comments by replacing all instances of <!-- with #*<!--*# and all instances of --> with #*-->*#
Intercepting the html before and after it enters the ckeditor is fairly straight forward and well documented. I found the following article that explains a little about how to get the ckeditor content on submit
How to update CKEditor content on form submit – equivalent of OnAfterLinkedFieldUpdate FCKEditor
The following question also covers this
Update editor content immediately before save in CKEditor plug-in
You can't.
The browser will rearrange those contents: http://jsfiddle.net/wPGLd/
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
alert(document.body.innerHTML)
}//]]>
</script>
</head>
<body>
<table style="width: 100%;" width="100%">
<tbody>
#foreach (var row in body.indexPageRow) {
foreach (var cell in row.teaser) {
<tr>
<td class="row">#Raw(cell.teaserContent.a.Html)</td>
<td class="row">#Raw(cell.teaserContent.div.InnerHtml)</td>
</tr>
}}
</tbody>
</table>
</body>
</html>