symfony twig javascript function undefined - javascript

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.

Related

Moving Embedded JS to Separate File

I want the embedded script in my page footer to be combined with other JS in a bundle.js file.
When I successfully add it to the file - the function below doesn't add the attributes to my external links as it before.
How do I adjust the code to make it work?
Combined JS
Placed in the footer
<script src="{{ '/assets/js/bundle.js' | url }}"></script>
Embedded Script
Placed in the footer - want to add to bundle.js
<script>
(function () {
const links = document.querySelectorAll("a[href^='https://'], a[href^='http://']")
const host = window.location.hostname
const isInternalLink = link => new URL(link).hostname === host
links.forEach(link => {
if (isInternalLink(link)) return
link.setAttribute("target", "_blank")
link.setAttribute("rel", "noopener")
link.setAttribute("data-splitbee-event", "External Link")
link.setAttribute("data-splitbee-event-type", link.hostname)
})
})()
</script>
Bundle File
---
permalink: "/assets/js/bundle.js.njk"
---
{% set js %}
{% include "../assets/js/main.js" %}
{% include "../assets/js/search.js" %}
// place embedded scrip in external-links.js
{% include "../assets/js/external-links.js" %}
{% endset %}
{{ js | minifyJs | safe }}

How to compare Django template language variables with javascript variables?

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.

Symfony2: AJAX request returns full page html

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.

Django jQuery not working?

This is what my template looks like:
{% extends 'typer/base.html' %}
{% load url from future %}
{% load staticfiles %}
{% block title %}{{ p_name }}{% endblock %}
{% block body_block %}
<script type='text/javascript'
src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script>
$('#user_passage_text').on('keyup', function(e) {
if ( e.which === 13 ) {
var time = (new Date()).getTime() - $(this).data('time');
$(this).data('time', 0);
console.log('Time passed : ' + time + ' milliseconds');
}else if ( !$(this).data('time') ){
$(this).data('time', (new Date()).getTime());
}
});
</script>
<h1>{{ p_name }}</h1>
<p>This passage is {{ p_wlength }} words, {{ p_clength }} characters long.</p>
{% if passage %}
<p><blockquote>{{ p_text_body|linebreaksbr }}</blockquote></p>
{% else %}
The specified text {{ p_name }} does not exist!
{% endif %}
<p>
Begin typing to start the test.
</p>
<textarea id="user_passage_text"></textarea>
{% endblock %}
All I want for this to do is print a message to the console to check that the function is working. The reason I'm confused about it not working is that I can run it on http://jsfiddle.net/d8c4z300/ perfectly fine. So why does the message print there but not when I run the django template?
you need $(function(){ ... }) (or $( document ).ready(function() { ... }); which is equal, only longer) around your js code:
so:
$(function(){
$('#user_passage_text').on('keyup', function(e) {
if ( e.which === 13 ) {
var time = (new Date()).getTime() - $(this).data('time');
$(this).data('time', 0);
console.log('Time passed : ' + time + ' milliseconds');
}else if ( !$(this).data('time') ){
$(this).data('time', (new Date()).getTime());
}
});
});
fiddle is working because you set it to onload which is almost equal to $(function(){ ... }) here.

Using Django Templates, how can I access values from my model in the JavaScript header?

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.

Categories

Resources