Is there a way to display a jinja variable name instead of it's value? - html

I'm writing a program in flask currently and I'm trying to see if I can display the name of a Jinja variable instead of the value it holds. For example:
{% set x = 0 %}
<button onclick="myFunction({{ x }})>
I'm trying to pass the variable into a javascript function but having the HTML show myFunction(x) instead of myFunction(0). Is there any way to do this?

Try:
for(var key in objects) {
var value = objects[key];
}

Related

Golang html template updating data [duplicate]

I have a Golang array I'm passing to my html file on the front end.
I know that
'{{ index .Array 0}}'
works and pulls the first element from the array. But I want to do a Javascript for-loop and print every element in the array like so
<script type="text/javascript">
function loop() {
html = ""
for(var i = 0; i<5; i++) {
html += "{{ index .Array " + i + "}}";
}
}
But this doesn't work. Something about separating the go array index string, HTML/Javascript doesn't like it and it won't load.
It's a syntactical error that I just can't pin down.
Any ideas?
You need to understand something:
Template actions such as {{index .Array 0}} are executed at server side in your Go application.
Javascript code is interpreted and run at client side in the browser.
The template parameter value used in template actions (Array in your example) does not exist at client side (e.g. as a Javascript object). And Javascript code is not run by the template engine. So the template parameter (value) and Javascript (execution) live in 2 different "spaces".
Having said that, it is not possible to mix template actions/variables and Javascript execution.
You have 2 options:
1) Do what you want to do with template actions.
2) Use the template to create Javascript code which when executed at the client side will construct/recreate the array as a Javascript object so it will be available for further Javascript processing.
Note that if you just want to loop over the array once, creating a Javascript array is not neccessary, you can simply render the JavaScript code that would be the loop body inside a {{range}} template action. See Simon's answer as an example to this.
Elaborating #1
You can use the {{range .Array}} action to loop over Array, and the block is executed for each element, pipeline set to the array element so you can output the array elements like this:
{{range .Array}}
{{.}}
{{end}}
Of course you can put anything else inside the block, not just the array elements. You can even access the current index like this:
{{range $idx, $value := .Array}}
Index = {{$idx}}; Element = {{$value}}<br>
{{end}}
Elaborating #2
Let's say your Array contains int numbers, you can recreate it in Javascript and loop over it in Javascript with a template like this:
<script>
var arr = [
{{range .Array}}
{{.}},
{{end}}
];
// Now you have a javascript array: arr, loop over it to do something:
html = "";
for(var i = 0; i < arr.length; i++) {
html += " " + arr[i];
}
</script>
Or since the template engine supports "rendering" arrays and slices as JavaScript arrays, you can simply write:
<script>
var arr = {{.Array}};
// Now you have a javascript array: arr, loop over it to do something:
html = "";
for(var i = 0; i < arr.length; i++) {
html += " " + arr[i];
}
</script>
You're not "passing a Golang array to the front end" .. your template is being rendered server side. That is an important distinction.
When you think about it like that .. the syntactic issue becomes clear. You are attempting to intermix Go's template syntax with Javascript right in the middle of expressions. That simply isn't correct. You should use a Go loop that, when rendered, produces valid Javascript for the client to consume:
var javaScriptHtmlVariable = "";
{{ range .Array }}
javaScriptHtmlVariable += '{{.}}';
{{ end }}
Which would render:
javaScriptHtmlVariable += 'One';
javaScriptHtmlVariable += 'Two';
javaScriptHtmlVariable += 'Three';
javaScriptHtmlVariable += 'Four';
// etc..

Html.Raw() in combination with Razor?

I am trying to add a <span> to my view when my session variable is not null.
The value of Session["error"] has the right value (I checked), but there is no <span> coming in my view when it is filled while the code DOES come into the IF statement.
#if (Session["error"] != null) { Html.Raw("<span class=\"alert\"> #Session[\"error\"].ToString() <span>"); }
Plz tell me what i need to change. I am a student and new to coding.
You need to add # to write the output of the function to the response stream. In short; #Html.Raw().
However, this is not how Razor code should be used. Instead you can embed HTML directly within your if, like so:
#if (Session["error"] != null)
{
<span class="alert">#Session["error"]</span>
}

Is there a simple way to have a local webpage display a variable passed in the URL?

I am experimenting with a Firefox extension that will load an arbitrary URL (only via HTTP or HTTPS) when certain conditions are met.
With certain conditions, I just want to display a message instead of requesting a URL from the internet.
I was thinking about simply hosting a local webpage that would display the message. The catch is that the message needs to include a variable.
Is there a simple way to craft a local web page so that it can display a variable passed to it in the URL? I would prefer to just use HTML and CSS, but adding a little inline javascript would be okay if absolutely needed.
As a simple example, when the extension calls something like:
folder/messageoutput.html?t=Text%20to%20display
I would like to see:
Message: Text to display
shown in the browser's viewport.
You can use the "search" property of the Location object to extract the variables from the end of your URL:
var a = window.location.search;
In your example, a will equal "?t=Text%20to%20display".
Next, you will want to strip the leading question mark from the beginning of the string. The if statement is just in case the browser doesn't include it in the search property:
var s = a.substr(0, 1);
if(s == "?"){s = substr(1);}
Just in case you get a URL with more than one variable, you may want to split the query string at ampersands to produce an array of name-value pair strings:
var R = s.split("&");
Next, split the name-value pair strings at the equal sign to separate the name from the value. Store the name as the key to an array, and the value as the array value corresponding to the key:
var L = R.length;
var NVP = new Array();
var temp = new Array();
for(var i = 0; i < L; i++){
temp = R[i].split("=");
NVP[temp[0]] = temp[1];
}
Almost done. Get the value with the name "t":
var t = NVP['t'];
Last, insert the variable text into the document. A simple example (that will need to be tweaked to match your document structure) is:
var containingDiv = document.getElementById("divToShowMessage");
var tn = document.createTextNode(t);
containingDiv.appendChild(tn);
getArg('t');
function getArg(param) {
var vars = {};
window.location.href.replace( location.hash, '' ).replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}

Set a new Variable in Assemble (or combine two comparison helpers)?

is there a way to set a new variable in a partial in assemble (assemble.io)? Or is it possible to combine two comparison-helpers, for example:
{#is somevar "yes" || anothervar "no"}
There's HTML in my partial which should only be shown if one of two different variables is true. If there's only one variable, i only write {{#is somevar "yes"}}, but i need that #is-helper for both variables.
I haven't found a way in the assemble-docs so i tried another way. I tried to do two #is-Helper like:
{{#is somevar "yes"}}
// HTML
{{/is}}
{{#is anothervar "no"}}
// HTML (the same as above)
{{/is}}
But this is really redundant... so i tried to set a variable inside both #is, for example:
{{checkvar = 0}}
{{#is somevar "yes"}}
{{checkvar = 1}}
{{/is}}
{{#is anothervar "no"}}
{{checkvar = 1}}
{{/is}}
So i only have to check for one variable (checkvar).
BUT all this wont work... So is there a way to do this in assemble?
Greetings
This would be something common to any Handlebars templates and not specifically Assemble.
Assemble uses handlebars-helpers and we've recently upgraded to Handlebars 3.0 so you can use a combination of subexpressions with the or and is helpers:
{{#or (is somevar "yes") (is anothervar "no")}}
<div>somevar = yes or anothervar = no</div>
{{/or}}
Edit: This might not work since the is helper is a block helper. You might have to write your own helper to just return the value. Either that or change somevar and anothervar to be truthy values instead of yes and no. Then you can just use the or helper directly:
{{#or somevar anothervar}}
{{/or}}

Handling checkboxes and getting values

I'm pretty new to MVC and I'm having a hard understanding how to get the values (basically the IDs) to checkboxes that I'm generating. Here are my checkboxes:
<div id='myCheckboxDiv'>
<input type="checkbox" onclick="checkAll(this)">Check All
#foreach (var form in #Model.DetailObject.DoaFormGroupDocuments)
{
<br>
var checkBoxId = "chk" + form.DocumentId;
#Html.CheckBox(checkBoxId, new { value = form.DocumentId, #checked = true });
#form.DocumentName;
}
</div>
Essentially what I want to do is get the ID to which ever checkbox is checked and save it in to a list after I click a save button at the bottom of the page.
I have run across something like this to handle everything but I'm not quite sure how to use it really...
var values = $('#myCheckboxDiv').find('input:checkbox:checked').map(function () {
// get the name ..
var nameOfSelectedItem = this.attr('name');
// skip the ‘chk’ part and give me the rest
return nameOfSelectedItem.substr(3);
}).get();
The only thing you need to think about is the value of the name attribute your checkbox(es) will have. The way you're handling it right now, your post body is going to have a fairly randomized collection of chkN-named parameters, where N is some number. The modelbinder will need something similarly named as a parameter to your action method in order to bind the posted values to something useful. That's a tall order for something that will be some what variable (the DocumentId values).
The best option would be to set up your checkboxes, instead, as a collection, which means giving them names chk[0], chk[1], etc. Then in your action you can accept a parameter like List<string> chk, and that will contain a list of all the values that were posted.