How to use bindings inside raw html? - javascript

How can one use dynamic attributes and bindings while rendering raw html. Suppose:
<script>
let name = 'Joseph'
let test = '<p>{name}</p>'
</script>
{#html test} <!-- Outputs: {name} instead of Joseph -->
I know, one would answer that, a better approach to this would be creating a component. But still I want to ask, if there is a way of using bindings inside raw html rendering?

You can't. But you can do this: {#html `<p>${name}</p>`}

Related

How to inject html using mustache

Following is my content:
const content = Testing mutache with html. click {{{link}}}.
Following is my mustache code:
Mustache.render(content, {link:'here'});
On screen, it is rendering as :
Testing mutache with html. click here.
What am I doing wrong?
The answer is you don't use the mustache in this way. To render HTML into a template you would have to use the rawHTML method as described here:
https://v2.vuejs.org/v2/guide/syntax.html#Raw-HTML
to Quote "The double mustaches interprets the data as plain text, not HTML. In order to output real HTML, you will need to use the v-html directive"

Binding value as html in stenciljs

I am having trouble rendering a value with custom html inside into an element.
ex:
this.title = 'Hello <b> stencil </b>'; << response value from an API
Binding:
<h1>{this.title}</h1>
I am expecting something same as innerHtml behavior in JavaScript.
You can use
<h1 innerHTML={this.title} />
This is not a good practice in JSX, it is against the idea of virtual DOM and it's not creating virtual nodes.
You should try like this
this.salute = 'Hello';
this.name='stencil';
Binding
<h1>{this.salute} <b>{this.name}</b></h1>
Or if it is a more complex situation, build another smaller component.
However using innerHTML will work, but should be used in different situations more details here(at the bottom of the page).

How to pass parameters to jquery via script tag

What my code does:
It switches out the class of a div when i push a button. So i can push a button and the class changes from "Class" to "SwitchToThisClass" which has a different set of properties.
<script src="JS/SideNav-ShowOrHide.js"></script>
Here is my code, how do i change it so i can put parameters in and i also want to use the same JS file to change multiple classes:
(function() {
var bodyEl = $('body'),
navToggleBtn = bodyEl.find('Class');
navToggleBtn.on('click', function(e) {
bodyEl.toggleClass('SwitchToThisClass');
e.preventDefault();
});
})();
For example like this code that takes parameters and is clean, i want to be able to use the same JS file with different parameters. I want to switch out 'Class' and 'SwitchToThisClass', and take parameters instead.
HTML:
<script src="http://path.to/widget.js" data-width="200" data-height="200">
</script>
Outside JS file:
<script>
function getSyncScriptParams() {
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript;
return {
width : scriptName.getAttribute('data-width'),
height : scriptName.getAttribute('data-height')
};
}
</script>
Hope this makes sense, thanks for the help in advance.
In your purpose what you propose does not make much sense since there are better ways and more accessible and that will also allow you to modularize functions and pass parameters. However you have the possibility to add custom attributes to HTML tags if it is your final decision.
As you continue editing your question I continue editing my answer so.
Solution using data HTML attribute. and data HTML attribute documentation.
I personally do not like use it for script tag and I can not recommend it way.
Why? Because your source is a file not a function. A file have not parameters (said in some way). 'Visual' HTML tags/elements or stuff that is structure of the page is more related with this data binding. Unless your intention is to manipulate the tag itself in the first instance. What I think is never.
I would never use it to pass parameters to a contained function in the file.
Of course I am here giving my opinion. The solution exist.
Also you are facing old browsers support in your case.
What I understand you want have some static values in specific html file used to pass throught to a JS function contained in a JS file.
What you can do is first import your JS file that contains your JS function:
<script src="JS/SideNav-ShowOrHide.js"></script>
We suppose you have a function I have call 'changeFunction' in this file. Your function need to have some input parameters and then you can do from your HTML inmediatly after your file import.
<script>
var classFrom = "class1";
var classTo = "class2";
changeFunction(classFrom, classTo);
</script>
or directly:
<script>
changeFunction("class1","class2");
</script>
By other hand if what you need is manage classes of specific items give a look to how to add/remove classes from raw JS

Are HTML allowed inside HTML attributes?

For example, lets say you have something like this:
<div data-object="{'str': '<h1>This is a nice headline</h1>'}"></div>
Is this allowed in HTML5 and will it render properly in all browsers?
Edit:
With properly I mean that the browser will ignore and NOT render the H1 in any way ;)
Yes, it's allowed as long as it's quoted correctly.
Will it render? The H1 element? No - because it's not an element, it's just a bit of text inside an attribute of the div element.
Yes, browsers won't render any HTML tags inside attributes. This is pretty much common when you want to move the element later so it would show up. The only problem is that this is not a way to go as this does not create an element in DOM, thus, it will be much slower.
Try to find a way or ask for an alternative/better way to reuse the element which is hidden when the page is loaded.
Yes it's allowed and possible, but to make it work you have to make it valid JSON by using double quotes:
<div data-object='{"str": "<h1>This is a nice headline</h1>"}'></div>
Now to parse it just have: (jQuery will parse it to JSON all by itself)
var element = $("div").eq(0);
var rawData = element.data("object");
var rawHTML = rawData["str"];
$(rawHTML).appendTo("body");
Live test case.

HTML generation in JS code

I'd like to know your thoughts about HTML code generation in my JS code.
I just think that the html.push("<tag>" + something + "</tag>") style pretty annoying.
I've already tried something with templates inside my HTML file (and put some placeholders therein), and then used its content to a replace the placeholders to my real values.
But maybe you guys have other ideas, possibly one using jQuery.
jQuery is the way to go. You can do things like this:
// create some HTML
var mySpan = $("<span/>").append("Something").addClass("highlight");
it is cross-browser compatible,
it is an easy to use syntax
There is also a templating plugin.
You can use createelement, appendchild, and innerHTML to do this.
Here's an article from A List Apart that uses these functions in the process of generating a dropdown menu.
jQuery has javascript template plugins like jBind and jTemplate. I haven't used them myself but I do recommend jQuery whenever possible.
A note on html generation, it is not searchable by search engines in most cases.
I'm a big fan of how PrototypeJS handles templates.
First you create an instance of the Template class and pass it a string containing the template HTML.
var tpl = new Template('Here is a link to #{sitename}');
Then you pass it data containing the values to replace within the template.
$('someDiv').innerHTML = tpl.evaluate( {link: 'http://www.stackoverflow.com', sitename: 'StackOverflow'} );
In the above example, I have a div with id="someDiv" and I'm replacing the contents of the div with the result of the template evaluation.
Resig has a little blog entry on creating a very lightweight template system.
There are a bunch of JQuery function that support this. In particular, you should look at append(content), appendTo(content) prepend(content) prependTo(content), replaceWith(content), after(content), before(content), insertAfter(content), and insertBefore(content).

Categories

Resources