I would like to include JavaScript inside a form widget in Symfony2, but quotes are escaped inside the JavaScript command, see:
{{ form_widget(form.sdf,
{ 'attr': { 'value': "document.MSketch.getMol('sdf');" } }
) }}
and the result I get:
<input type="hidden" id="form_sdf" name="form[sdf]" required="required" value="document.MSketch.getMol('sdf');" />
I have read this topic : Twig and autoescaping
But autoescape false is not working when using it like this:
{% autoescape false %}
{{ form_widget(form.sdf,
{ 'attr': { 'value': "document.MSketch.getMol('sdf');" } }
) }}
{% endautoescape %}
How to have quotes?
EDIT: Using raw filter isn't helping:
{% set cmd = 'document.MSketch.getMol("sdf");' %}
{{ form_widget(form.sdf, { 'attr': { 'value': cmd|raw } } ) }}
But raw filter is working outside of the form_widget, so where is the problem?
Have you tried to simply escape quotes? \' or \"
Related
I am trying to retrieve below field values in nunjucks following below template
Json data -
{
"user": {
"custom": [
{
"payload": "{ f_name=user, l_name=name, source=facebook, contact=email }"
}
]
}
}
Nunjucks Template -
{% set u = user %}
{% set data = u['custom'][0]['payload'] %}
Hello {{ data }}
This returns the below output
Hello { f_name=user, l_name=name, source=facebook, contact=email }
However, I would like to get the individual elements from the {{data}}
How can I fetch the f_name, l_name, source, contact fields from the above json data.
Please note the payload is a string and not a json object
You don't show us how user is pulling your JSON data into nunjucks, so I'll just spill out my take on this. Take advantage of the JavaScript split method, and the template engine loops and filters to give you the results you need.
I'm assuming there is more to your JSON data. If so, here is a short guide to help pull your 4 string items out of payload.
The JSON Data:
//sample JSON Data
const sampleData = [{
"user": {
"custom": [{
"payload": "{ f_name=user, l_name=name, source=facebook, contact=email }"
}]
}
}];
module.exports = sampleData;
The View:
{% for string in mSampleData %} //mSampleData is similar to your "user" template object.
{% for mval in string['user']['custom'] %}
{% set mstring = mval['payload'].replace('{', '').replace('}', '') %}
{% set marray = mstring.split(",") %}
{% set fname = marray[0].replace('f_name=', '') %}
{% set lname = marray[1].replace('l_name=','') %}
{% set source = marray[2].replace('source=','') %}
{% set contact = marray[3].replace('contact=','') %}
<p>{{fname}}</p>
<p>{{lname}}</p>
<p>{{source}}</p>
<p>{{contact}}</p>
{% endfor %}
{% endfor %}
The results:
user
name
facebook
email
Trying to get Bootoast to work on my website, where I try to pass a message. You can see the code below. Using Django-bootstrap for front-end.
BASE.HTML
<script srs="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.css">
<script>
function toast(message, type) {
bootoast.toast({
position: 'bottom-center',
message,
type,
});
}
{% if messages %}
{% for message in messages %}
toast('{{ message }}', '{{ message.tags }}')
{% endfor %}
{% endif %}
</script>
VIEWS.PY
#login_required(login_url="/sign-in/?next=/customer/")
def profile_page(request):
user_form = forms.BasicUserForm(instance=request.user)
customer_form = forms.BasicCustomerForm(instance=request.user.customer)
if request.method == "POST":
user_form = forms.BasicUserForm(request.POST, instance=request.user)
customer_form = forms.BasicCustomerForm(request.POST, request.FILES, instance=request.user.customer)
if user_form.is_valid() and customer_form.is_valid():
user_form.save()
customer_form.save()
messages.success(request, 'Your profile has been updated')
return redirect(reverse('customer:profile'))
return render(request, 'customer/profile.html', {
"user_form": user_form,
"customer_form": customer_form
})
So the error I'm getting is this:
(index):197 Uncaught ReferenceError: bootoast is not defined
I'm blind or isn't this defined?
<script srs="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.js"></script>
Should have been
<script src="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.js"></script>
I am wanting an application to be able to check whether the user that is currently logged in is "test2". I'm using Django and running the following code:
<script>
console.log('{{ request.user }}')
{% if request.user == "test2" %}
console.log('The user that is currently logged in is test2.')
{% else %}
console.log('There was an error.')
{% endif %}
</script>
And my console is logging the following:
test2
There was an error.
Why is this? How do I get the application to recognise that "test2" is logged in?
request.user.username
<script>
console.log('{{ request.user.username }}')
{% if request.user.username == "test2" %}
console.log('The user that is currently logged in is test2.')
{% else %}
console.log('There was an error.')
{% endif %}
</scrip
This may be because request.user is actully object, but __str__ is giving username attribute of User. So:
{% if request.user.username == "test2" %}
console.log('The user that is currently logged in is test2.')
{% else %}
console.log('There was an error.')
{% endif %}
*Note:- I am assuming test2 is username and it is unique.
Since the logic is in template, it is being evaluated at server side. This means that request.user is not a string, it is a user instance.
The reason why the console.log('{{ request.user }}') prints out the username is when you print, __str__ is called which returns the username.
So you need to check with the correct field, i.e. the user.username.
<script>
console.log('{{ request.user }}')
{% if request.user.username == "test2" %}
console.log('The user that is currently logged in is test2.')
{% else %}
console.log('There was an error.')
{% endif %}
</script>
I am a little bit stuck on my Symfony code.
Let me explain,
I have a todo-list table in my database containing :
An ID called : id
A name field called : todo
And 3 others fields that don't matter : "completed", "created_at", "updated_at".
Before going further : here is my codes,
The concerned Controller :
/**
* #Route("/todos/delete/{id}", name="todo.delete", methods={"POST"})
* #param Todo $todo
* #param ObjectManager $manager
* #param Request $request
* #return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function delete(Todo $todo, ObjectManager $manager, Request $request)
{
$manager->remove($todo);
$manager->flush();
if ( $request->isXmlHttpRequest()) {
return $this->redirectToRoute('todo.home', [
'id' => $todo->getId()
]);
}
throw $this->createNotFoundException('The todo couldn\'t be deleted');
}
The view :
{% extends 'base.html.twig' %}
{% block title %}Todos{% endblock %}
{% block content %}
<br>
<form action="{{ path('todo.create') }}" method="post">
<input type="hidden" name="token" value="{{ csrf_token('todo-create') }}"/>
<label for="todo">Todo</label>
<input type="text" id="todo" name="todo" class="form-control input-group-lg" placeholder="Create a new todo">
</form><br>
{% for todo in todos %}
{{ todo.todo }}
Update
x
{% if todo.completed %}
Completed !
{% else %}
Mark as completed
{% endif %}
<hr>
{% endfor %}
{% endblock %}
We focus on :
x
The JavaScript :
$(document).ready(function () {
$('.js-delete-todo').on('click', function (e) {
e.preventDefault();
var url = $(this).attr('href');
delTodo(url);
function delTodo(url) {
$.ajax({
type: "POST",
url: url
}).done(function (data) {
$('#id').remove();
}).fail(function () {
alert('Could not be deleted');
});
}
});
});
Actually,
Everything seems to work : it does a POST ajax request, and delete the row in my table in my database.
The only issue is that I have to hit F5 to see it.
How can I make it work without reloading the page nor hitting the F5 hotkey?
In your symfony code you should return JSON format like here.
Wrap your todo in container like this
{% for todo in todos %}
<div id="todo-{{todo.id}}">
// your todo staff here
</div>
{% endfor %}
Then change your javascript to
function delTodo(url) {
$.ajax({
type: "POST",
url: url
}).done(function (data) {
var id = JSON.parse(data).id;
$('#todo-' + id).remove();
}).fail(function ()
alert('Could not be deleted');
});
}
I am extending keystone.js to support multiple languages in the models.
The original model looks like this:
Post.add({
title: { type: String, required: true },
publishedDate: { type: Types.Date, index: true },
//... more irrelevant fields
});
My extended model looks like this:
Post.add({
title: { type: String, required: true },
en: {
title: { type: String },
publishedDate: { type: Types.Date, index: true },
//... more irrelevant fields
},
es: {
title: { type: String },
publishedDate: { type: Types.Date, index: true },
//... more irrelevant fields
},
//... more languages following the same pattern
});
I am having an issue using the nested publishedDate properties within the view templates.
Original view code that works with the original model:
{% if post.publishedDate %}
<br>on {{ post._.publishedDate.format('MMMM DD, YYYY') }}
{% endif %}
Adjusted view code for my new model (this is where I am having the issue):
{% if post[lang].publishedDate %}
<br>on {{ post[lang]._.publishedDate.format('MMMM DD, YYYY') }}
{% endif %}
Using post[lang].xxxxxx I can refer to all of the other items in my post (for example post[lang].title.
Am I missing something that is causing these nested underscore functions to fail with the following error?
non_object_property_load Error thrown for request" /en/blog
TypeError: Cannot read property 'publishedDate' of undefined
EDIT:
It gets more peculiar... below seems to work:
{% if post[lang].publishedDate %}
<br>on {{ post._[lang].publishedDate.format('MMMM DD, YYYY') }}
{% endif %}
If anyone can offer up an explanation of why this works (or a better way to accomplish this), I would really appreciate it.
#JRulle, I assume the error is on the following line:
<br>on {{ post[lang]._.publishedDate.format('MMMM DD, YYYY') }}
The issue is that the underscore methods belong to the List object. For example, to access the underscore methods for post.en.publishedDate you would use the following syntax: post._.en.publishedDate.format('MMMM DD, YYYY')
You should change the above line to:
<br>on {{ post._[lang].publishedDate.format('MMMM DD, YYYY') }}