I am trying to iterate through a dictionary in my django template and save the values to window.obj, but it is not working.
views.py:
def myView(req):
...
myDict = {'foo':"[1,2]", 'bar':"[3,4]"}
return render(req, 'myPage.html', {'myDict':myDict})
myPage.html:
<script type="text/javascript">
window.obj = {}
window.obj["foo"] = "{{ myDict.foo }}";
{% for key, value in myDict %}
window.obj["{{ key }}"] = "{{ value }}";
{% endfor %}
</script>
...
<script>
console.log(window.obj.foo); //prints {foo: "[1,2]"}
console.log(window.obj.bar); //prints undefined
</script>
Note: I can't use myDict.foo on my actual project
What am I missing here?
{% for key, value in myDict.items %}
Related
I've got something like this in my Django template:
<script>
var selected_direction = $("#id_direction").val();
{% for bus_stop in bus_stops %}
{% if bus_stop.direction == selected_direction %}
// Do something //
{% endif %}
{% endfor %}
</script>
I can do everything with bus_stops until it reaches the {% if %} statement. How can i compare javascript variable with django variable?
/Edit
Maybe the question was not constructed properly. However i solved my problem by doing this:
<script>
var selected_direction = $("#id_direction").val();
var temp_direction;
{% for bus_stop in bus_stops %}
temp_direction = "{{ stop.direction }}";
if (temp_direction == selected_direction){
////////
///////
}
{% endfor %}
</script>
you can compare this condition
{% if bus_stop.direction == selected_direction %}
by converting you template value to js value, and compare it in js if condition as follows.
if(selected_direction == '{{bus_stop.direction}}')
{
//code here
}
Here is a post that explains how they work together. There is a injection risk involved with this. Maybe make an ajax call for your data and do everything in javscript.
I'm using twig to declare a var user:
<script type="text/javascript">
{% if user is defined %}
var user = {
example: {{ userjson | raw }}
};
{% endif %}
</script>
This checks to see if a user is logged in, if not my console returns this:
Uncaught ReferenceError: user is not defined
I want to be able to display a message if the user is not defined but I can't think of a way to do that. Right now I have this:
if(user){
console.log('hello');
} else {
console.log('undefined');
}
// This checks is the user information
var userId = user.example.id;
console.log(user.example.money);
Ok so I figured this out:
<script type="text/javascript">
{% if user is defined %}
var user = {
example: {{ userjson | raw }}
};
{% else %}
var user = false;
{% endif %}
</script>
Then I just check to see if the var user is false, and if it's not then I do something else.
I'm trying to get a simple AJAX request to work in Symfony2. It seems that the request is never reaching the controller. Instead of alerting the number '123', the AJAX request returns the HTML of the current page (index.html.twig). I have a feeling that since the pattern of the AJAX route is pointing to the current page I am on, the AJAX response is being filled with the output of the current page rather than getting the response from the Controller. Is there any way that I can get just the value from the Controller? Any help would be greatly appreciated.
Here is my Twig template (index.html.twig):
{% extends 'base.html.twig' %}
{% block body %}
<a href="123" class="test">Test</div>
{% endblock %}
{% block javascripts %}
{% javascripts '#AppBundle/js/jquery.js' %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.test').on('click', function(){
var id = jQuery(this).attr('href');
jQuery.post('{{path('task_ajax')}}',
{data: id},
function(response){
alert(response);
}
);
return false;
});
});
</script>
{% endblock %}
Here is my routing.yml file:
task_ajax:
pattern: /jobs
defaults: { _controller: AppBundle:Ajax:task }
requirements:
_method: POST
Here is my controller:
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class AjaxController extends Controller
{
public function taskAction() {
$request = $this->container->get('request');
$data = $request->query->get('data');
return new Response($data);
}
}
check routing order. Move Ajax route to first place.
I'm trying to use an external JS file in my twig. The goal is just to verify client's input.
When I put directly my script in my Transfert.html.twig , my script is well executed but when I used an external file with assetic nothing happen. The link created by assetic is good(I can see my script when i click on it in my web page source code).but firebug says
"SyntaxError: expected expression, got '<'
<script type="text/javascript">" "ReferenceError: verifyMontant is not defined"
I registred my bundle into app/config/config.yml:
" bundles: [FASTTransfertBundle]", so I guess no problem form here
Now this is my code: Transfert.html.twig:
{# src/FAST/TransfertBundle/Resources/views/Default/Transfert.html.twig #}
{% extends "FASTTransfertBundle::layout.html.twig" %}
{% block title %}{{ parent() }} - Index{% endblock %}
{% block body %}
{{ form_label(form.montant) }} {{ form_widget(form.montant,{'attr':{'onblur':'verifyMontant(this)'}}) }}
{% javascripts '#FASTTransfertBundle/Resources/public/javascript/verifyTransfert.js' %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
{% endblock %}
And this is my javascript file :
<script type="text/javascript">
//color if wrong
function changeColor(field,error)
{
if(error)
field.style.backgroundColor = "#fba";
else
field.style.backgroundColor = "";
}
function verifyMontant(field)
{
var montant= field.value.replace(/\D+/g,'');
var regex = /^\-?[0-9]*\.?[0-9]+$/;
if(!regex.test(field.value)){
changeColor(field, true);
return false;
}
else if(montant.length != 11){
changeColor(field, true);
return false;
}
else{
changeColor(field,false);
return true;
}
}
</script>
You must remove
<script type="text/javascript">
from your javascript file.
Using Django, I can successfully read and display values from my model in the content segment of my template, but I can't get the values from my model in the head segment of my template.
Here's the code -->
view.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from host.models import Event
def EventSingle(request, slug):
return render_to_response('event.html', {'eventobject': Event.objects.get(slug=slug)})
event.html:
{% extends "base.html" %}
{% block extrahead %}
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var variable1;
variable1="click worked";
//variable1={{ eventobject.datetime }};
$(document).ready(function () {
$("#pic").click(function (b) {
alert(variable1);
});
});
</script>
{% endblock %}
{% block content %}
<div id="eventobject">
<p>{{ eventobject }}</p>
<p>{{ eventobject.location }}</p>
<p>{{ eventobject.datetime }}</p>
<img id="pic" src="{{ eventobject.image1.url }}" />
</div>
{% endblock %}
When clicking on the image, an alert box pops up with the text "click worked", but if I comment out variable1="click worked"; and un-comment variable1={{ eventobject.datetime }}; nothing happens when I click on the image. Can I not use model references in the head section of django template? All other references to the model in the content block display the values from the DB properly.
I guess eventobject.datetime must be a string or python datetime object.
If it is a string, change your code to :
variable1= "{{ eventobject.datetime }}" ;
If it is a datetime object, use django template filter :
variable1= "{{ eventobject.datetime|date:"D d M Y" }}"
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
If you do not put the quotes, the javascript statement looks like:
variable1 = 2013-05-30 ;
which is INCORRECT javascript syntax, the quotes are needed.
Per Django docs, you can use a date filter to format date:
variable1= '{{ eventobject.datetime|date:"d-m-Y" }}';
Additionally, you can also set DATE_FORMAT (or DATETIME_FORMAT) setting to set a project-wide default for displaying such values.