Advice on WYSIWYG architecture for an Ember app - ember.js

I'm having a hard time coming up with a solution for this problem.
I'm building a WYSIWYG designer, for micro sites. The templates for these microsites will be supplied by an intermediate user, and the end-user will manipulate these templates. So, there are really two groups of users of the app: template-buiders, and end-users. Think MailChimp.
This means my Ember app will start off with a template from a template-builder, say
<h1>An awesome product</h1>
<h2 contenteditable="true">Subtitle away</h2>
<p>{{#if optionA}} One thing {{else}} Another thing {{/if}}<p>
and the end user, having chosen this template, will then be able to customize it. There are a few requirements:
There will be static, uneditable portions of the page (h1 above)
There will be static, editable portions of the page (h2 above)
There will be options that affect the layout, style, etc. (p above)
So far, my attempts have lead me to build a handlebars helper that takes a string and a context, and returns a rendered template. This is because the above template will actually be coming over from a database, as a string - remember, it's user-generated.
That means, in my application's template, it would look like
<div class="preview">
{{preview-userTemplate template context}}}
</div>
where
template: '<h1>An awesome product</h1><h2 contenteditable="true">Subtitle away</h2><p>{{#if optionA}} One thing {{else}} Another thing {{/if}}<p>',
context: {optionA: true}
Now, this actually works, in the sense that it will update if context is updated, so I can add controls along the sides for the end-user to manipulate those options. So I have those (more of less) under control.
It's the WYSIWYG content editing that is giving me trouble. In the above template (from my template-builder users), I want them to be able to add contenteditable="true" to places in their templates where the end-users can change the content.
Now, these changes need to be saved. Ideally, I would be able to retrieve the instance view's template back from the DOM, after the inline edits have been made. Is this possible? The original {{data}} placeholder would need to be preserved.
Alternatively, I could make a view/component, so the template-builder would do something like this:
<h1>An awesome product</h1>
{{#editable}}
<h2>Subtitle away</h2>
{{/editable}}
<p>{{#if optionA}} One thing {{else}} Another thing {{/if}}<p>
but this seems like it would require a good deal of finagling to get the edits to stick - I'm not even sure right now how I'd go about it.
What do you guys think? Is there an easier solution that I'm overlooking? Thanks for any pointers!

Related

Template inheritance in Ember

I have several unrelated pages that use Layout A, and another set of unrelated pages that use Layout B. It's as simple as that, but I can't figure out how to do this in Ember the DRY way.
I understand that template nesting is equal to route nesting, but I do not want to nest routes because it'd mean the URL will be also nested. I want to nest templates only because the pages are unrelated.
What I want to achieve is essentially template inheritance.
I expected this to work, but Ember throws an error.
// app/routes/samePage.js
import Ember from 'ember';
export default Ember.Route.extend({
renderTemplate(){
this.render('somePage', {
into: 'layoutA'
});
}
});
This is the error I get:
ember.debug.js:18015 Assertion Failed: You attempted to render into 'layoutA' but it was not found
I also get this warning. It tells me to read this link, but I don't think it helps me.
DEPRECATION: Rendering into a {{render}} helper that resolves to an {{outlet}} is deprecated. [deprecation id: ember-routing.top-level-render-helper] See http://emberjs.com/deprecations/v2.x/#toc_rendering-into-a-render-helper-that-resolves-to-an-outlet for more details.
Here is what layoutA.hbs would look like. I know you can't have {{outlet}} multiple times in a same template, but you probably get what I want to achieve.
<div class="header">
{{outlet}}
</div>
<div class="content">
{{outlet}}
</div>
<div class="footer">
{{outlet}}
</div>
How do I go about doing this in Ember? It sounds like such a basic task that needs to be more clear. Do I need to implement a template inheritance helper (like the one shown here) by myself? Or perhaps, there's already an Ember add-on for that?
Unfortunately, there is no such thing as template inheritance in Ember. But there are two features that allows to reuse html-code:
Components is well-known feature of Ember. It allows to have a re-usable template and/or js code to control such template appearance and behaviour. Component has it's own context, so all data should be passed to it via properties. I recommend to use components for custom ui elements or when you need to reuse a part of template with some logic (for example, top navigation with user menu which depends on authentication can be moved to component). There is also a trick that allows to emulate template inheritance with components using multiple {{yield}}. Maybe that's what you want.
Partials seems to be less known (they are not even mentioned in official guide for 2.x) but very useful. This helper ({{partial}}) renders any template in current context. I recommend to use it when you need to break a big template into parts.
These features are enough to reduce an amount of duplicated code. You probably can't reduce duplicated code to zero with them, but in my opinion it's not critical. Just move what you can to partials/components and your templates will be clear enough. Use that trick with component and yield if you want to emulate inheritance.
Update
Couple of words about partials
If you google "ember component vs partial", you can see a few blog posts and answers on SO, in which ppl say "don't use partials". In many cases without explaining why. The main points that I found are:
Components are more isolated, decoupled and testable. And I agree with that.
Partials may be deprecated and removed in future. However, that was first said in year 2015, but at this moment partials are still there and not deprecated.
When I suggest to use partials?
When you have a big template that is hard to maintain and you can't drop that route in parts. It happens if you use some css-framework (like bootstrap or semantic-ui) and need to implement a couple of big 3-4 step forms, or add a couple of modals or display some complex entity. Using components in this case is unneccessary (you will not use them on any other page) and their isolation adds headache (you will need to pass data that you need to display as properties and add some action(s) to get user input in case of forms).
Why I suggest to use partials in this case?
There is no need to reuse such partial, we just want to break template for easier maintenance. For example, to have each step of 3-steps form in it's own .hbs file rather than having one big template.
If partials will be deprecated, it's easy to move that pieces back to one big template.
It sounds to me like your solution is pretty simply just to use Ember components. Ember components have their own template which can nested into your route's template with {{name_of_component}}, however using components does not affect the routing.
Perhaps I am misunderstanding your need, but it seems to me like this is the easy fix. Read about it here. If I am misunderstanding the question, please clarify!
What I want to achieve is similar to using named outlets, so I can output some content into a specific place. However, it seems like Ember's recommend way to do this is to use ember-elsewhere.
The documentation says:
Before named outlets were introduced to Ember the render helper was used to declare slots for this.render in routes. This usage is not common in modern, idiomatic applications and is deprecated. In general, the pattern of named outlets or named render helpers is discouraged. Instead use of ember-elsewhere or another DOM-redirection library should better serve these use cases.
I found this add-on to be easier to understand over partials and components.
This, or using partials/components is probably the best we can get as Handlebars do not have a template inheritance feature.
Or, I should be changing the way I'm creating the app, and use routes to do template nesting. That's probably the Ember way.

django cms [aldryn newsblog] replace template for plugin

I need to replace same plugin template on different subpages - e.g. on frontpage I need specific slider template for latest articles, in detail article I need small list, on search result without images etc.
[note: everything about aldryn newsblog app - I don't mean my own plugin!]
*(something like custom template per plugin instance)
How to replace it ? Extending template is not quite what I need - inheritance is from bottom - from lower subtemplate to base.html - but that plugin have hardcoded lower template.
Tons of IF block in template is irrational then we think in MVC.
*( like here Render Django-CMS plugins differently on different splaceholders/templates )
Or maybe just write custom template with using hardcoded including plugins ? But using django cms placeholder editor is very useful and it'll be better to keep working in that way :///
So, I create front.html base template for frontpage,
put some plugins to placeholders - and need to replace subtemplates for this plugins only in this front.html and keep subtemplates for that plugin in other places - this is main goal.
It will be the best, when django cms / aldryn newsblog provide option "custom template" per plugin instance :|
( like this one http://www.ilian.io/django-cms-plugins-with-selectable-template/ )
If I understand your question correctly (it's late here), you need a way to override plugin templates on a plugin instance basis because hacking django templates is not the way to go (I agree).
Django CMS does allow you to override plugin templates on an instance basis.
As shown in http://docs.django-cms.org/en/develop/how_to/custom_plugins.html?highlight=get_render_template#the-simplest-plugin
In your CMSPluginBase subclass add the following:
def get_render_template(self, context, instance, placeholder):
# criteria goes here
return 'sometemplate.html'
As far as how to know which template to render when (criteria), you can do a few things.
Use the page's reverse id:
page = instance.page
templates = {
'homepage': 'plugin_home.html',
'about': 'plugin_about.html',
'contact': 'plugin_contact.html',
}
return templates[plugin.page.reverse_id]
This approach has a few drawbacks:
Relies on plugin being bound to a page. (plugins can live outside of pages)
Can only work with pages that have reverse id set and reverse ids
are unique per page which means you would have to list reverse id
for every page you want to change template for.
Use a page extension to set a category per page:
Checkout http://docs.django-cms.org/en/develop/how_to/extending_page_title.html
With this approach you can then set some sort of category to multiple pages and so you can target multiple pages in one shot like so:
page = instance.page
extension = get_page_extension(page) # Check out docs for this
templates = {
'category_1': 'plugin_category_1.html',
'category_2': 'plugin_category_2.html',
'category_3': 'plugin_category_3.html',
}
return templates[extension.category.name]
Pros:
Can target multiple pages in one shot
Cons:
Relies on plugin being bound to a page.
A bit more complex
Use a template context variable:
In your templates, depending on how you're rendering your plugins, you can
provide a context variable like so:
{% with category='category_1' %}
{% placeholder 'content' %}
{% endwith %}
or
{% with category='category_1' %}
{% render_plugin yourplugin %}
{% endwith %}
Then in your get_render_template method you can access this context variable and do the following:
# Use .get() to provide fallback
category = context['category']
templates = {
'category_1': 'plugin_category_1.html',
'category_2': 'plugin_category_2.html',
'category_3': 'plugin_category_3.html',
}
return templates[category]
Pros:
No extra models.
Can target multiple pages in one shot.
Cons:
The only one I can think of is these random {% with %} in
templates.
I completely missed the newblog part, so in order to override the newsblog plugins or any plugin, just subclass the plugin class you want to override and unregister the original and then register yours, make sure yours has the same class name.
Maybe you can make the whole template logic above into a mixin to use throughout your project.
I've always wanted to give Zinnia a look, but I'm too far into working with NewsBlog on a site right now to do it (and blogs have already been posted and whatnot). You can always just add a few extra placeholders in the template (it's not the most efficient looking thing ever, but it's no load on the framework if you add a placeholder and leave it blank), that way they aren't static, and then you can put whatever plugins you want to inside of them. You can customize each component in NewsBlog pretty easily by just adding whatever you want in the structure mode. Things get trickier when it comes to having multiple blogs that act differently, but even then, as long as you're not adding components into the static placeholders provided by NewsBlog (or as I so elegantly learned it, "don't put the stuff in the blocky-things with the pins next to them), you can create different namespace for the different blogs (either in the admin, under "Configs" in the NewsBlog section, or when creating a new page and hooking it to the NewsBlog app), and you can have different templates on different blogs.
EDIT: This is a really excellent resource for touching up NewBlog without throwing the baby out with the bathwater (after three months of learning DjangoCMS, I'm still finding myself referencing it for fine-tuning pieces of NewsBlog, and to refresh my grasp on templatetags and other things that are overwhelming and have quickly left my brain along the way): https://www.django-cms.org/en/blog/2016/02/16/build-a-website-without-knowing-python-django-part-two/
*I linked to part two, as the first part deals with how to initially setup a project, and I assumed it probably wasn't relevant. Then again, if you're using Aldryn, there are some useful bits in there that can extrapolate if you're having trouble with customizing the boilerplate (or other things you'd like to configure that an Aldryn setup handles for you -- which is super awesome most of the times, but when it's not super awesome, it's usually super frustrating :)

Dynamic templates with Django and Ajax

My question is a bit generic in that my problem is a broad one. I have been working with django for some time, and I really want to move more into doing very dynamic web pages where actual page reloads aren't common.
I have read about the different popular javascript frameworks available, and I always feel like I am missing part of the puzzle, particularly in templating.
What are some of the best practices for keeping my templating code as non redundant as possible. I get the impression that a lot of templating logic will make it's way into the JS in addition to my django templates. I want to avoid situations where I am writing templating code in two different places.
For a very basic example, let's say I am writing some template code inside Django for an input field that has a set number of attributes. I have then also written in JS that when I click on a button, another input field of the same type is generated with all the appropriate attributes. In practice this could be a form that takes an arbitrary amount of e-mail addresses. The problem I see is that when I want to change something about that input field, I need to do it in two places.
Is there a particular development paradigm or work flow that I am unaware of? How are issues like this generally avoided?
Recommendations on frameworks would be amazing too!
as you mentioned above:
Use Django Template language. Pass the data from view to template dynamically.
Read Django Template Language documentation.
For JS :
its better to write your js in home.html.... use {% include %} tag for other html

Switching out the Ember.js application template

This is quite possibly a stupid question given my lack of experience with Ember JS at the moment. However I was wondering how one would approach an application that may have a few fundamentally different structural layouts. From what I do understand the application template is designed to display elements that will always be there.
Consider the following:
Login screen
No Header
No Sidebar
No Footer
Has Login box
Main Application
Has Header
Has Sidebar
Has Footer
Drawing part of the application
No Header
Has Canvas
Has Inspector
.. Etc
The question becomes how can one adjust the main application layout to cater to fundamental structural differences in an application. I'm assuming that one could leave the application template blank and render these static bits in where needed, but I think that opens yourself to repeating configurations. IE one wouldn't want to have to specify a layout for each possible route, or maybe you would?
Just looking for some pointers / best practice.
Thanks!
Totally opinion based here, but I think this is a perfect case for a blank application and different routes which are displayed completely differently.
App.Router.map(function(){
this.resource('login');
this.resource('home');
this.resource('drawing');
..... etc
});
And then you can share/reuse templates super easy, so maybe in the home template you'd have something like
{{render 'header'}}
other content
{{render 'footer'}}
then in your drawing template you'd have something like this
drawing stuff
{{render 'footer'}}
or whatever makes sense for your application.

Django: calling DB queries from a template

I've got a Django site that has a sidebar with a variety of different boxes that could go in it depending on the page. For example, "Most recent comments" or "Latest tweets" or "Featured story." These boxes all require database queries to run.
I could simply add a most_recent_comments and whatever other variable are needed to the View for each page. But this feels brittle. I'd like to be able to move and change boxes just by editing the templates.
So my other thought was I could add all the variables that all the boxes might need to every page with a Context Processor, but is the ORM smart enough to only run the queries for pages that actually use those variables? Or is it going to hit the database even if I have no boxes on a page?
So what I think I want is some kind of custom tag where I could just say {% most_recent_comments_box %} and it would be smart enough to load whatever variables it needs from the database and then call a little template file. Is this the right approach? How do I accomplish that?
This is the use case for custom template tags. Read this article (written by one of the people behind Django).
One addition to Django since that article was written is the inclusion tag shortcut, which implements the "call a little template file" approach you mention.
So my other thought was I could add all the variables that all the boxes might need to every page with a Context Processor, but is the ORM smart enough to only run the queries for pages that actually use those variables? Or is it going to hit the database even if I have no boxes on a page?
Yes, the ORM will be smart enough to do that. Django QuerySets are lazy: https://docs.djangoproject.com/en/dev/topics/db/queries/#querysets-are-lazy