Ember.js Strip Binding Tags - ember.js

Is there a way to strip binding tags from an ember.js infused handlebars template? I would like to be able to extract just the html without any of the metamorph script tags.
I have this related question but wanted to ask this more general question as well.

You can use the unbound Handlebars helper to do this at the individual property level.
There is work being done on an #unbound block helper, which would be nice for what you're trying to do: https://github.com/emberjs/ember.js/pull/321
Another approach is to, in your views, specify a plain Handlebars template. None of the output will be bound.
App.UnboundView = Ember.View.extend({
template: Handlebars.compile("output is: {{msg}} here"),
msg: "not bound"
});
Here's a jsFiddle example: http://jsfiddle.net/ebryn/zQA4H/

Here's a better way
{{unbound propertyName}}
http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_unbound

In case anyone needs this functionality, I created a small jquery plugin to do it:
# Small extension to create a clone of the element without
# metamorph binding tags and ember metadata
$.fn.extend
safeClone: ->
clone = $(#).clone()
# remove content bindings
clone.find('script[id^=metamorph]').remove()
# remove attr bindings
clone.find('*').each ->
$this = $(#)
$.each $this[0].attributes, (index, attr) ->
return if attr.name.indexOf('data-bindattr') == -1
$this.removeAttr(attr.name)
# remove ember IDs
clone.find('[id^=ember]').removeAttr('id')
clone
Still hoping there is a better way.

Related

How can I write custom handlebars in Ember js?

js:
Ember.Handlebars.registerHelper('demo-helper', function (property, options) {
console.log('demo helper');
return '<li><a> '+ msg+'</a></li>';
});
hbs :
{{#demo-helper}} msg {{/demo-helper}}
How can I wrap hi (inner html of handlebar) with any custom tag?.I know that component has tag parameter that encapsulates html with given tag. But it supports only one tag. I want to encapsulate with multiple tags like
<li><a>innerhtml</a></li>
This is what components are for. They have can have an arbitrarily sized template. You can use {{yield}} to nest other html inside the component.
See https://guides.emberjs.com/v2.15.0/components/wrapping-content-in-a-component/.
component template:
<div><div><div>{{yield}}</div></div></div>
usage:
{{#my-component}} Hello world {{/my-component>}}
Components are very powerful and have many other options, see the guides for more info. They are the best resource.

How to render Ember component on same line

This Ember template code...
<div class="detail bedrooms">
<span>Number of bedrooms:</span> {{rental.bedrooms}}
</div>
<div class="detail temperature">
<span>Current Temperature:</span> {{city-temperature location=rental.city}}
</div>
...results in this rendering...
How could one get the "25C" text to render on the same line as "Current Temperature" in the same way that "San Francisco" is on the same line as "Location"?
I have tried getting the city-temperature component to return only text, but (secondary question here) is it even possible for a component to return only text if the text is from a remote ajax request since the promise seems to need a DOM element to append to?
This Ember app is available here on GitHub. It's a modified version of the official Ember.js tutorial app with this "Current Temperature" detail added.
The problem is that; city-temperature is a component; and by default ember components is assigned div as their tags. Due to this; the content of city-temperature starts at a new line.
What can you do? Play with css and make sure div tag of city-temperature does not start at a new line; but instead floating right within the owner div. The second option is making city-temperature component tagless; so that it does not start at a new line. To achieve that; you can just declare:
tagName: ''
within city-temperature.js. You can see the following twiddle to see the second option I mentioned.
After reading your comments; I have forked your repository and made minor modifications to achieve what you want. You can check my repository and my corresponding commit to see what I changed.
Basically; I really did not like the idea that weather service is returning a DOM element. I have changed it to return an instance of ember promise (I mean Ember.RSVP.Promise). Within city-temperature.js I just set a retrieved weather value from weather service and set it to the component instead of making DOM modification. Finally; I modified city-temperature.hbs to render weatherValue and added a simple css item in order to prevent weather-container div to insert a new line break.
I am not sure; whether you will like my solution or not; but I guess you will retrieve the visual appearance you want. You can always rely on promises for async tasks; you do not need to create DOM elements and pass them around to components and append them to somewhere within DOM tree of the corresponding component. I believe one of the reasons we are making use of a framework like Ember is to prevent such DOM modifications. Best regards.
An ember component adds a div by default. If you don't want to add this div tag, you need to set tagName to an empty string.
That's called tagless component.
Further, for your case, you can give a tagName='span' so you will not need a span in your template.
export default Ember.Component.extend({
tagName: 'span',
classNames: ['weather-container'],
weather: Ember.inject.service(),
//rest of your code...
});

backbone/marionette attaching HTML into a region

I'm beginning to use Marionette within an existing backbone application. I've got some HTML which I want to append into a region. In pure backbone, I could just do this.$el.append(html_code) and that was all. As far as I can see, marionette regions allow only to operate on views (which have to implement the render method). Calling append on marionette region throws 'undefined method' errors.
Is it possible to attach plain HTML to a marionette region?
No, it's not possible to inject plain html into a Marionette.Region.
Theoretically you could access a regions DOM element with someRegion.el or someRegion.getElement(), but this must be done after rendering (which at least isn't possible inside a Marionette.View with standard behaviour).
But you can achieve the desired result by using a specially crafted Marionette.ItemView:
#someRegion.show(new Marionette.ItemView({template: '<h1>gach</h1>'}));
You maybe also should have a look at Marionette.Renderer .
a Marionette ItemView will look for a template and will call render on that template, so when you show the view in the region the html will be displayed just fine with out the need of you defining a render method.
MyImtemView = Backbone.Marionete.ItemView.extend({
template : "#myTemplate"
});
var myItemView = new MyItemView();
myLayout.aregion.show(myItemview);
this should work if you save your html in a template like this
`<script id="myTemplate" type="text/template">
<div><p>your html<p>
</div>
`
EDIT
you can also declare a render function in your view in case you need to generate and modify your html like this.
MyImtemView = Backbone.Marionete.ItemView.extend({
template : "#myTemplate",
render : function (){
this.$el.append(HMTL); //so here you work your html as you need
}
});
var myItemView = new MyItemView();
myLayout.aregion.show(myItemview); //the render function of your view will be called here
I ran into the same problem and tried the answers explained here, but I'm also using require.js and kept getting an error for the #my_view template not being found. If anyone can clarify where does Marionette look up the templates by default, that would be great.
Instead, I solved it by using the text.js plugin for underscore.js. This way you actually can use a plain html file as the template, without the need for nesting it in a script tag. Here's how I did it.
define(['backbone', 'underscore', 'marionette', 'text!tmpl/my_view.html'], function(Backbone, _, Marionette, view_t){
var MyView = Backbone.Marionette.ItemView.extend({
template : function(serialized_model) {
//define your parameters here
param1 = erialized_model.param1;
return _.template(view_t)({
param1: param1
});
}
});
return MyView;
});
I placed the text.js plugin in the same lib directory as all my other js libraries and my main.js for require declares the path to the templates as
'tmpl': '../../templates',
My project structure looks like this
root
index.html
js
main.js
app
App.js
views
MyView.js
lib
require.js
text.js
backbone.js
underscore.js
jquery.js
backbone.marionette.js
templates
my_view.html
My template 'my_view.html' simply looks like this.
<h1>THIS IS FROM THE TEMPLATE!!!</h1>
Worked perfectly. I hope you find it useful.
Using a view
var myHtml = '<h1>Hello world!</h1>';
var myView = new Marionette.ItemView({template: _.constant(myHtml)});
myRegion.show(myView);
Marionette.Renderer.render takes either a function or the name of a template (source code). _.constant creates a function that returns the passed-in parameter.
Attaching HTML
Alternately, the docs for Marionette.Region mention overriding the attachHtml method, see Set How View's el Is Attached.

Ember Handlebars Embed ID

I am trying to use ember to show a dynamic list of found content. The problem is that when I try to put handlebars in html attributes, everything breaks.
RegApp.PatronsFound = Ember.CollectionView.create
tagName: 'table'
content: []
itemViewClass: Ember.View.extend
template: Ember.Handlebars.compile("<td><button onclick='alert({{content.id}})'>{{content.name}}</button>")
RegApp.PatronsFound.appendTo('body')
When it is fed a piece of content with the ID of 3 and the name FOO, I want this html to be generated:
<button onclick="alert(3)">FOO</button>
Instead, I get this:
<button onclick="alert(<script id=" metamorph-4-start'="" type="text/x-placeholder">3<script id="metamorph-4-end" type="text/x-placeholder"></script>)'>FOO</button>
You can use
{{unbound content.id}}
to arbitrarily insert values into your templates. Normally, such values are wrapped in metamorph tags which allow the displayed value to be bound to the backing value, and updated whenever the backing value changes. This only works if the output is regular HTML, not, in this case, spanning event handlers and embedded JS. {{unbound}} inserts the value at that property path once, without metamorph tags, and without being updated if that value changes in the future.

django admin list_filter too long

I have a list_filter with loads of sectors. This list, on the right side of the page, is too long.
Can I use an input select field instead since I can't choose more than one sector?
I have seen this before, screenshots, but I can not find the way to do this.
edit:
I have a custom FilterSpec not a list_filter
You can write your own custom FilterSpec (custom admin list filter).
This feature is not part of the Django code yet; it is planned for version 1.2. You'll need to apply this patch to the Django code: http://code.djangoproject.com/ticket/5833.
There are many examples on stackoverflow on how to do that, e.g: https://stackoverflow.com/a/1294952/342473.
http://lincolnloop.com/blog/2011/jan/11/custom-filters-django-admin/
The long list that you said comes from the default template 'admin/filter.html', in django/contrib/admin/templates/admin/filter.html, of builtin ListFilters.
There are several ways to customize it:
Globally override 'admin/filter.html'. Render select tag instead of ul tag if the count of choices hit certain limit. This affects all list filters in admin. The select tag should have onchange event handler like
<select ... onchange="location.href=this.options[this.selectedIndex].value">
Set template attribute in your specific ListFilter instance, to the name of the customized filter template. The content of the template is like #1. Django 1.4+ is required for this.
Add javascript in the ModelAdmin instance to convert HTML content inside the ul tag to select tag as soon as DOM has been fully loaded.
This is how i resolved it (jQuery):
$('#changelist-filter ul').each(function(){
var maxlength = 10;
if ($(this).children().length > maxlength )
{
var list=$(this),
select=$(document.createElement('select')).insertBefore($(this).hide());
$('>li a', this).each(function(){
console.log($(this).parent().attr('class'));
var target=$(this).attr('target'),
option=$(document.createElement('option'))
.appendTo(select)
.val(this.href)
.attr('selected', $(this).parent().attr('class'))
.html($(this).html())
.click(function(){
if (target==='_blank'){
window.open($(this).val());
}
else{
window.location.href=$(this).val();
}
});
});
list.remove();
}
});