Set template in html after changes - handlebars.js

I have a next a method how compile and set in DOM my html:
export function initHTMLOperator(container) {
if (container.template) {
const template = SF.handlebars.compile(container.template);
const html = template(container);
const elem = document.getElementsByTagName(container.id)[0];
elem.innerHTML = html; // set compiled template
}
}
container.template has a template
container - it is object with variables for template.
After compilation I set html in DOM.
But i have a problem when changing input i recompile template and losing focus.
Is it possible to update a template in the DOM without innerHTML?
I mean update template but not set full html, only changes.

What you want is something like react and not handlebars then, you should use a virtual DOM and apply only changes, but handlebars doesn't provide such functionality. So no if you want your new template then you have to replace the whole content with something like innerHTML. But if the only problem is loosing your focus you can save it before replacing your content and reset the focus once the template has been replaced.

Related

Render a react component on a wordpress page

We currently have our website built with Wordpress and I have built a component in React that we want to conditionally render on the page.
I have the component built and bundled with Webpack for production but cannot figure out how to add it to our website and render the component on the page
edit I will also need to conditionally render the component (form submit, button click, etc.)
Has anyone successfully done this?
Since you've built and bundled your component already, you only need to do three things:
Add the bundled JavaScript (the Webpack output) as a script tag in whatever page you want the component to be on (preferably at the bottom of the <body>).
Example: <script src="wp-content/react/bundle.js"></script>
Add the root element that React will bind to to the same page.
Example: <div id="react-root"></div>
In your component file, render the component to the root element.
Example: ReactDOM.render(<Component />, document.getElementById('react-root'));
To dynamically show and hide the React component based on something that happens outside the component file, you need to create a way to connect the outside (the DOM) to the inside (React). The easiest way to do this is with a global variable attached to window.
In your React component, add the componentWillMount method that defines a global variable:
componentWillMount() {
window.showComponent = (option) => {
// "option" should be true or false
this.setState({ display: option });
}
}
Based on the value passed to setState above, you'll need to add the display property to your component's state:
constructor(props) {
super(props);
this.state = {
display: false
};
}
Now to make the component show or hide based on the value of this.state.display inside the render() method:
render() {
if (this.state.display) {
return (
...
)
} else {
return null;
}
}
All that's left to do is use showComponent(true) or showComponent(false) in your code that handles the form.
In your React project add the file to the global scope (window) like this:
window.myReactComponents = {
myFirstComponent: () => <MyFirstComponent/>
}
Once this is bundled reference the bundlejs file on your non-react page.
In your non react page in the global scope reference ReactDOM.render with the root element which it should use to render like this:
window.useComponent = {
renderMyFirstComponent : ReactDOM.render(
window.myReactComponents.myFirstComponent(),
document.getElementById('myReactElement')
)
};
That's it!
Live example
ReactDOM.render Documentation

How make a dynamic value in MeteorJS

I need to set a variable or array in meteor JS which whenever changes. Wherever it is used on the page changes.
So far I have tried to set values in session.
let in = Session.get("in");
and this in HTML. The following works fine. This changes whenever it detects a change in array
{{#each in}}
<span class="selectable-tags"> {{this}} </span>
{{/each}}
But whenever I try to add these tags to other div using following. Then the ones added to other div does not change.
"click .selectable-tags"(e, t) {
// sets the tags inside the Method box on click
var el = e.target.cloneNode(true);
el.setAttribute('contenteditable', false);
document.querySelector('[contenteditable]').appendChild(el); },
using meteor with blaze UI. This can be used as reference link
Edit: Session.get or set is given for reference . This was to tell that these values are changing as they on any event triggered wherever set.
You need to add a helper that returns the session variable and show the helper in your html code :
Template.yourtemplate.helpers({
inHelper: ()=> {
return Session.get('in');
}
)}
And in html :
<div>{{inHelper}}</div>
Every modification on in by Session.set('in', newValue) will change your HTML.

Wordpress - Changing Background-Color of Multiple Divs

I have multiple DIV elements on my page with the class "grid-item-container"
I want to make the background-color of each one different. I will set an array of 5 different colours that can be set.
There is a script available here that seems to do this: http://jsfiddle.net/VXG36/1/
$(document).ready(function() {
var randomColors = ["green","yellow","red","blue","orange","pink","cyan"];
$(".random").each(function(index) {
var len = randomColors.length;
var randomNum = Math.floor(Math.random()*len);
$(this).css("backgroundColor",randomColors[randomNum]);
//Removes color from array so it can't be used again
randomColors.splice(randomNum, 1);
});
});
I cannot however get it to run on my page. Is there something in this script that needs to be amended to make it Wordpress friendly?
Kind regards
Dave
You might wan't to wrap it in something like this:
jQuery(document).ready(function($) {
// Inside of this function, $() will work as an alias for jQuery()
// and other libraries also using $ will not be accessible under this shortcut
});
The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link. Read more about it in Codex here.
Also, change $(.random) to $(.grid-item-container), this targets the class of your div.

how to attach events to generated html of a template in Meteor 0.8 with Blaze

I'm using Meteor 0.8 with Blaze and I want to attach events dynamically to HTML contents generated using UI.toHTML of a template. The functionality I am looking for is the alternative to Spark.attachEvents in Blaze.
What I have done so far is that I have created the following template to be used like a widget/component.
<template name="postLinks">
<div id="link-popover-wrapper" >
<ul class="link-popover">
{{#each linkOptions}}
<li><a tabindex="-1" class="link-action" id="link-{{value}}" href="#">{{label}}</a>
</li>
{{/each}}
</ul>
</div>
</template>
And the template is used in Helper of the myPostItem template.
Template.myPostItem.events({
'click .post-item-link-picker': function (evt, tmpl) {
var tempData = {linkOptions:[{label:'Favorite', value : 'favorite'}, ...]};
// Get the HTML content of the template passing data
var linkContent = UI.toHTML(Template['postLinks'].extend({data: function () { return tempData; }}));
// Attach events to the linkContent like in Spark
/*Spark.attachEvents({
'click link-action': function (e, tmpl) {
alert("Component item click");
}
}, linkContent);*/
// Popover the content using Bootstrap popover function
}
});
So my requirement is to attach events to a dynamically generated HTML contents.in the linkContent like Spark.attachEvents after the following line as mentioned in above code.
var linkContent = UI.toHTML(Template['postLinks'].extend({data: function () { return tempData; }}));
Hope somebody can help to find a way to do this in Meteor 0.8 with Blaze.
The reason that Spark-generated HTML could be directly inserted into the DOM is because it had "landmarks" - annotations that could be processed into events and handlers when the DOM nodes were materialized.
Blaze works differently - it inserts a UI component into the DOM directly and attaches events, using the UI.render function. It cannot directly attach template events to the DOM if you use UI.toHTML because there are none of the annotations that Spark had for doing this.
I'm also using Bootstrap popovers in my app, and as far as I know there's no clean way to insert reactive content into a popover. However, you can approximate it with a hack in the following way:
In the content callback of the popover, render the template with UI.toHTML - a nonreactive version of the content. This is necessary because otherwise the popover won't be sized and positioned properly.
Using a Meteor.defer call, replace the popover contents with reactive content, so they'll continue updating while the popover is open.
Because Bootstrap uses jQuery, you should be fine with removing reactive logic properly, for now. Future versions of Meteor will probably have easier ways to do this.

z3c.form and Plone - add custom css file to a form without using a custom template

In a project I'm working on we've defined a simple z3c.form, it looks like this.
class IImportCandidateForm(Interface):
csv_file = NamedFile(title=_(u'CSV file'))
class ImportForm(form.Form):
fields = field.Fields(IImportForm)
ignoreContext = True
def updateWidget(self):
super(ImportForm, self).updateWidget()
... snip ...
#button.buttonAndHandler(u'Import')
def handleImport(self, action):
data, errors = self.extractData()
if errors:
self.status = self.formErrorMessage
return
file = data["csv_file"].data
Is there a way to associate a custom css file with this form without first wrapping it in a custom page template with the form?
No, there isn't. Unless you use a form wrapper, the form's template renders only the form and not the entire page.
In you are using this form in a custom view, you have a class style added to the body class (something like template-yourviewname). So you can add you CSS rules to a main CSS resource, loaded in every page, but prefix every rule with .template-yourviewname.

Resources