I have basic task to print something from template tag.
It works if I open html file from filesystem, but it prints nothing if I run this from django web-server.
For example:
<li ng-repeat="k in [0, 1, 2]">{{k}}</li>
Output if I open file from filesystem:
<li>0</li>
<li>1</li>
<li>2</li>
And if I get file from Django web-server:
<li></li>
<li></li>
<li></li>
This problem is driving me crazy :(
If Django is messing with the {{}} tags, you can change the template tags like this:
var app = angular.module('myApp', []);
app.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('((');
$interpolateProvider.endSymbol('))');
});
http://docs.angularjs.org/api/ng.$interpolateProvider
Be careful while using (( )). You can get problems with function calls inside (( )).
Also note the use of third-party directives (components) that use {{ }}. Your configuration will break them.
See https://stackoverflow.com/a/11108407/457375
Related
So, I've been editing a website and have many JavaScript functions that utilize the Contexts that the views.py file passes to the page. Until now, these functions have been contained in the base.html file and so have been loaded onto every page directly. However, to make things cleaner, I copy and pasted all the functions to an external .js file. Now, rather than use the contexts, the functions consider them to be literal strings.
Example:
$('#title').text('{{ event.name }}');
The above line will actually set the text of the element to say "{{ event.name }}" rather than the name of the event. Any ideas on how to fix this? I really don't want to keep these functions in the base file where they can be seen by anyone who inspects the page source.
It doesn't matter if you put your javascript functions in an external file or in your base.html it would still get exposed to the user. Only a minification of the file would actually help to trick the user from seeing the actual values but with javascript all your code is public.
Why you're having this problem is because when you rendered the javascript inline (in your base.html) you had access to the template context.
This is no longer the case and the Django template engine doesn't interpolate your {{ event.name }} anymore.
The problem you're facing as well is a good one. You should never mix and match javascript with Djangos template language or any template language for that matter and the only way of fixing it is to
a) start pulling the values from the DOM ie. render a proper DOM
b) to start to fetch the values from the server, traditionally using AJAX.
And the smallest example that I can muster at the moment is below:
Your view:
def my_django_view(request):
return HttpResponse(json.dumps({'meaningoflife':42}), mimetype='application/json')
Your HTML
<input type="hidden" id="myMeaning" value="{{ meaningoflife }}" />
Your javascript
var meaning = document.querySelector('#myMeaning').value;
alert(meaning); //should alert 42.
In your view you return some form of render_to_response which takes a template argument and a context argument. What the render_to_response function does is read your template, and replace all {{ placeholders }} with the values passed via the context dictionary.
Templates are essentially a complex version of this
"""
<h1>{{ person.name }}</h1>
<p>{{ person.phone_number }}</p>
""".format(person)
The problem is the templating engine does not know files specified by a scripts src attribute is actually a Django template. To fix this don't use the script src attribute. Instead do something like this.
<!--base.html-->
<h1>Site Title</h1>
<p>Some content</p>
<script>
{% include 'jsfile.js' %}
</script>
Using the include statement should do the trick.
I want to add to the way html is indented in vim. I'm doing django development and I would like to indent whenever a django template tag is used. Currently, using filetype indent, it does not indent after the template tags. So currently my code looks like this:
{% do_something %}
<div>
<p>Hello</p>
</div>
{% end %}
And I'd like for it to recognize the {% %} as a tag and indent like so:
{% do_something %}
<div>
<p>Hello</p>
</div>
{% end %}
Is there a filetype plugin for this or a way I can add {% %} to the list of things that should be indented after?
When you have filetype indent on for an html file it will use the indenting rules found in the ../vim/vim73/indent subdirectory in file html.vim.
The braces you want to use as signaling indent of next line are, I'm sure, not treated in html.vim because they're not part of html. You can alter the rules in html.vim to get it done the way you want.
See :h indent-expr for a bit of info and you will also want to look at other files in the /indent directory to see how it works.
There is an alternate html.vim you can get at vim website, maybe it is better than html.vim that ships with Vim:
http://www.vim.org/scripts/script.php?script_id=2075
There is a pending pull request for the django.vim project to include an alternative django-custom vim implementation from Steve Losh. This works, for the most part, better than the default one.
Is there a way to replace the main tag on jquery-tmpl ?
Example:
var data = {Name: 'Pele', Languages: ["Portuguese","English","Spanish"]};
So on a script tag we define the following template
Name: ${Name}
{{each Languages}}
I speak $value
{{/each}}
What I wanted to change is ...
Istead of using {{each}} I'd use something like $$each$$
Instead of ${Name} I'd use something like $#Name$
You may be asking yourself why I wanna do this.
The main reason is when I because on the project we're working on uses Django and when we put code like {{each}} (even on script tag with type set to text/html) Django view engine think it's a server tag and tries to render it like if it were a server side tag.
Update:
What I'm looking for is a way to Set a Delimeter on jQuery-tmpl like the one that is avaiable on Mustache.js
http://mustache.github.com/mustache.5.html (look for Set Delimiter)
Thanks.
Sure, if you want a literal { in your HTML, use templatetag with openblock.
{% templatetag openblock %}
If you want a literal }, use closeblock:
{% templatetag closeblock %}
So if you want {{each}} in your HTML, use:
{% templatetag openblock %}{% templatetag openblock %}each{% templatetag closeblock %}{% templatetag closeblock %}
A different approach would be to define the template in a js file which is not processed by django as a template.
If that is not possible another alternative to Dominic's approach would be to define variables for '{{' and '}}' maybe jqtmpl_open and jqtmpl_close accordingly and use them in template like this:
{{ jqtmpl_open }}each Languages{{ jqtmpl_close }}
This would be more readable in the template.
Changing a delimiter for jquery-tmpl is complicated. By looking at the code it seems that {{ is hard coded within some regular expressions there.
var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]* (<[\w\W]+>)[^>]*$|\{\{\! /,
newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = [];
The only solution would be to fork the jquery-tmpl for your project and change these hard coded regular expressions to accommodate your needs.
This question has already been asked here jquery template tags conflict with Django template! but I thought I would add from my experience.
In a nutshell, I've added this custom "raw" template tag to my jquery-tmpl/django projects: http://www.holovaty.com/writing/django-two-phased-rendering/
I am trying to display Django source code from a Django template. However, I cannot find a tag similar to HTML's pre or xmp.
Here's the code
Also, I have a block with the same name which springs the error.
If your view puts the source code in a context variable called source, your template might look like this:
<pre>
{{ source|escape }}
</pre>
The escape filter will escape certain characters to make sure the HTML is rendered correctly.
If you just want to display hard coded template source in your template, there are two options.
Use HTML escaping to do so and remove your XMP tags.
{ instead of }
} instead of {
Or use the templatetag template tag:
{% templatetag openbrace %} instead of }
{% templatetag closebrace %} instead of {
etc.. refer to link
i don't really sure if i understand:
If you want show django template code try change '{' and '}' to
{ and }
After that django will not recognize it as var.
EDIT: another way to tell django not to parse code is here :) http://docs.djangoproject.com/en/dev/ref/templates/builtins/#templatetag
Django has a special template tag for this purpose.
use verbatim template tag
{% verbatim %}
...
{% endverbatim %}
I have a base.html template that contains a list of links.
Example:
<div id="sidebar1">
<ul>
<li>Index</li>
<li>Stuff</li>
<li>About Me</li>
<li>Contact Me</li>
</div>
Then I have in my views.py a definition for each of index.html, stuff.html, about.html and contact.html. Each of those templates simply derive from a base.html template and set their own respective titles and contents.
My question is about the above /stuff I have a class="current".
I'd like to make the current page that I'm on have that class attribute.
I could set a different variable in each view like current_page="about" and then do a compare in the template with {% ifequal %} in each class element of each link , but that seems like duplicating work (because of the extra view variable).
Is there a better way? Maybe if there is a way to get the view function name that the template was filled from automatically I would not need to set the extra variable? Also it does seem like a lot of ifequals.
Here's an elegant way to do this, which I copied from somewhere and I only wish I could remember where, so I could give them the credit. 8-)
I assign an id to each of my pages (or all the pages within a section) like this:
In index.html: <body id='section-intro'>...
In faq.html: <body id='section-faq'>...
In download.html: <body id='section-download'>...
And then an id for the corresponding links:
<li id='nav-intro'>Introduction</li>
<li id='nav-faq'>FAQ</li>
<li id='nav-download'>Download</li>
And the in the CSS I set a rule like this:
#section-intro #nav-intro,
#section-faq #nav-faq,
#section-download #nav-download {
font-weight: bold;
/* And whatever other styles the current link should have. */
}
So this works in a mostly declarative way to control the style of the link that the current page belongs in. You can see it in action here: http://entrian.com/source-search/
It's a very clean and simple system once you've set it up, because:
You don't need to mess about with template markup in your links
You don't end up using big ugly switch statements or if / else / else statements
Adding pages to a section Just Works [TM]
Changing the way things look only ever means changing the CSS, not the markup.
I'm not using Django, but this system works anywhere. In your case, where you "set their own respective titles and contents" you also need to set the body id, and there's no other Django markup required.
This idea extends easily to other situations as well, eg. "I want a download link in the sidebar on every page except the download pages themselves." You can do that in CSS like this:
#section-download #sidebar #download-link {
display: none;
}
rather than having to put conditional template markup in the sidebar HTML.
Haven't used Django, but I've dealt with the same issue in Kohana (PHP) and Rails.
What I do in Kohana:
<li><a href="/admin/dashboard" <?= (get_class($this) == 'Dashboard_Controller') ? "class=\"active\"" : NULL ?>>Dashboard</a></li>
<li><a href="/admin/campaigns" <?= (get_class($this) == 'Campaigns_Controller') ? "class=\"active\"" : NULL ?>>Campaigns</a></li>
<li><a href="/admin/lists" <?= (get_class($this) == 'Lists_Controller') ? "class=\"active\"" : NULL ?>>Lists</a></li>
What I do in Rails:
<li><a href="/main" <%= 'class="active"' if (controller.controller_name == 'main') %>>Overview</a></li>
<li><a href="/notifications" <%= 'class="active"' if (controller.controller_name == 'notifications') %>>Notifications</a></li>
<li><a href="/reports" <%= 'class="active"' if (controller.controller_name == 'reports') %>>Reports</a></li>
I see only a couple of ways of doing it, while avoiding repeated ifequals:
Javascript. Something along the lines of (jQuery):
var parts = window.location.pathname.split('/');
var page = parts[parts.length-1];
$('#sidebar1 a[href*=' + page + ']').addClass('current');
Change your views to contain a list of pages with their associated titles and URLs and create a {% for %} loop in your template, which will go through that list, and add a single {% ifequal %}.
Option 2 being the favorite from where I stand. If the logic for all of your pages is the same, and only the templates differ, you might consider using the FlatPages model for each of your pages. If the logic is different, and you need different models, you might consider using a menuing app of some sort. A shameless plug: I have a menuing app of my own
If you add the request context processor, it's pretty straightforward:
settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth' # admin app wants this too
)
Now you have access to the HttpRequest, which contains the request path. Highlighting the current page is a simple matter of checking if the path matches the link's destination, i.e., you're already there:
<li><a class="{% if request.path == '/' %}current{% endif %}" href="/">Index</a></li>
<li><a class="{% if request.path == '/stuff/' %}current{% endif %}" href="/stuff/">Stuff</a></li>
<li><a class="{% if request.path == '/about/' %}current{% endif %}" href="/about/">About Me</a></li>
<li><a class="{% if request.path == '/contact/' %}current{% endif %}" href="/contact/">Contact Me</a></li>