How to embed dynamic Ruby code to "javascript" section in Slim templates? - ruby-on-rails

One way:
javascript_tag do
== "var all_product_ids = #{existing_ids.to_json};"
== "var products_json = #{#filter.data.to_json};"
or:
= %Q{
var all_product_ids = #{existing_ids.to_json};
var products_json = #{#filter.data.to_json};
}
are there any better solutions for this?

In Slim
javascript:
var all_product_ids = "#{existing_ids.to_json}";
var products_json = "#{#filter.data.to_json}";

javascript:
var all_product_ids = #{raw existing_ids.to_json};
var products_json = #{raw #filter.data.to_json};

From https://github.com/slim-template/slim
Text Interpolation paragraph
SLIM escapes HTML by default.
To avoid the same use #{{content}} for #{content}

what i prefer to do, is to keep all the javascript in a separate file.
for example, i would do it as follows(jquery):
in your layout:
...
<body data-product-ids="<%= existing_ids.to_json %>"
data-products-json="<%= #filter.data.to_json %>">
.. in js:
// create your application namespace
$.myapp = {};
$.myapp.allProductIds = $.parseJSON( $('body').attr('data-product-ids') );
$.myapp.products = $.parseJSON( $('body').attr('data-products-json') );
so, you'll then use it in js like so:
$.myapp.allProductIds

I had a similar problem with this. Using the code that others have provided didn't work for me because slim was html escaping my variable. I ended up using Gon. This one is for Sinatra, but they have a gem for Rails as well. Hope it helps others having similar problems.

create a _your_erb_file_contain_javascript_code.erb first
And then in your slim file javascript: part:
#{ conditions ? (render 'your_erb_file_contain_javascript_code') : nil}

javascript:
var isAdmin = "#{current_user.admin? ? 1 : 0}";

Related

Svelte: Dynamic Tailwind-Class from Variable

How can I apply a tailwind class, if another var is true ... the follwoing does not seem to work.
This works
<script>
let svgColor = 'text-red-400'
</script>
<p class="{svgColor}">Test</p>
But this does not
<script>
let svgColor = 'text-red-400'
let svgVisible = true;
</script>
<p class="{svgVisible ? {svgColor} : ''}">Test</p>
By wrapping the svgColor with the curly braces you are effectively making an object with the prop svgColor.
The correct syntax would be:
<p class={svgVisible ? svgColor : ''}>Test</p>

using katex, '&' alignment symbol displays as 'amp;'

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.

How do I get the ASP.Net MVC Password HTML Helper to show characters as I type?

I'm using the Password HTML Helper in MVC5 to hide the social security number as it is entered.
#Html.Password("s", null, new { #maxlength = 9, autocomplete = "off" })
The problem I see with it is you just see dots as you type. Is there any way the helper behavior can be modified to show the characters you are typing in for a second or two then have them transformed to dots? That behavior would let the user confirm they are typing in the correct character. If the helper behavior cannot be modified is there another way to accomplish this?
I found this fiddle maybe you can use this as an option
http://jsfiddle.net/Ngtp7/
$(function(){
$(".showpassword").each(function(index,input) {
var $input = $(input);
$('<label class="showpasswordlabel"/>').append(
$("<input type='checkbox' class='showpasswordcheckbox' />").click(function() {
var change = $(this).is(":checked") ? "text" : "password";
var rep = $("<input type='" + change + "' />")
.attr("id", $input.attr("id"))
.attr("name", $input.attr("name"))
.attr('class', $input.attr('class'))
.val($input.val())
.insertBefore($input);
$input.remove();
$input = rep;
})
).append($("<span/>").text("Show password")).insertAfter($input);
});
});

How do I use ViewBag string in partial view javascript

I am returning this from a partial view:
<script>
document.getElementById("login").style.visibility = "hidden";
document.getElementById("displayname").innerHTML = #ViewBag.DisplayName
</script>
The second script line, however, does not work.
How to write this correctly?
Greg
#Html.Raw("document.getElementById(\"displayname\").innerHTML = " + #ViewBag.DisplayName)

How can I add page numbers to PDFKit generated PDFs?

I have multiple pages generated using PDFKit. How can I add page numbers to the bottom?
PDFKit.configure do |config|
config.default_options = {
header_right: "Page [page] of [toPage]"
}
end
kit = PDFKit.new(body_html)
Read all detailed documentation here:
http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf-0.9.9-doc.html
PDFKit is just a wrap up for wkhtmltopdf application that is written in C.
you need to specify a footer like this:
kit = PDFKit.new(your_html_content_for_pdf, :footer_html => "#{path_to_a_footer_html_file}")
then in the footer file have this:
<html>
<head>
<script type="text/javascript">
function subst() {
var vars={};
var x=document.location.search.substring(1).split('&');
for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}
var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];
for(var i in x) {
var y = document.getElementsByClassName(x[i]);
for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];
}
}
</script>
</head>
<body style="margin: 0;" onload="subst();">
Page <span class="page"></span> of <span class="topage"></span>
</body>
</html>
elements of classes 'frompage','topage','page','webpage','section','subsection','subsubsection' will get substituted with the appropriate data
I did page number with PDFKit, just by adding this:
%meta{:name => 'pdfkit-footer_right', :content => "[page]"}
in my haml file, in my RoR project.
For some weird reason, ( perhaps because I'm using slim ) - I have to use single quotes around the content, instead of double quotes - or else it attempts to escape the brackets and raw text "[page]" shows up, so try single quotes if you run into this issue with your pages.

Resources