symfony2 twig how to join string with object variable - symfony

I am trying to make a connection like this:
{% set img_src='images/ksiazki/'~{{new_book.tytul}}~'.jpg' %}
But I am still getting this error:
A hash key must be a quoted string, a number, a name, or an expression
enclosed in parentheses (unexpected token "punctuation" of value "
What is wrong?

You don't need {{ and }} as you are already inside a twig block {% ... %}
Modify your code as follows
{% set img_src='images/ksiazki/'~ new_book.tytul ~'.jpg' %}

Related

Replace for URL not found in twig

I am trying to delete some part of my url (string) in twig, and I can not do it. The result is not that I expect:
"http://local.myurl.com/en/node/8"|replace("en/node/8", "")
I expect:
"http://local.myurl.com/"
And the result is:
"http://local.myurl.com/en/node/8"
You can try json format like this :
{% set url = "http://local.myurl.com/en/node/8" %}
{{ url|replace({"en/node/8" : ""}) }}

Pass additional parameters to django_table2 TemplateColumn

In my django project I have a lot of tables which return models. The last column is mostly an Action-Column where users may edit or delete an instance. How do I proceed if I want to pass additional arguments to TemplateColumn if in some tables I want an edit and delete button and in other tables I only need an edit and info button? I want to use the same template.html but with conditions in it. Here what I have in Table:
import django_tables2 as tables
from select_tool.models import DefactoCapability
class DefactoCapabilityTable(tables.Table):
my_column = tables.TemplateColumn(verbose_name='Actions', template_name='core/actionColumnTable.html')
class Meta:
model = DefactoCapability
template_name = 'django_tables2/bootstrap-responsive.html'
attrs = {'class': 'table table-xss table-hover'}
exclude = ( 'body', )
orderable = False
And how do I check perms on the actions in order to display the button or not?
Quoting the TemplateColumn docs
A Template object is created [...] and rendered with a context containing:
record – data record for the current row
value – value from record that corresponds to the current column
default – appropriate default value to use as fallback
row_counter – The number of the row this cell is being rendered in.
any context variables passed using the extra_context argument to TemplateColumn.
So you could do something like this:
my_column = tables.TemplateColumn(
template_name='core/actionColumnTable.html',
extra_context={
'edit_button': True,
}
)
The context also contains the complete context of the template from where {% render_table %} is called. So if you have 'django.template.context_processors.request' in your context_processors, you can access the current user using {{ request.user }}.

web2py orderby datetime out of order

I'm writing a simple web app in web2py that stores and retrieves some data from a database. To keep the entries in chronological order, my table has an attribute which stores a date time. Like so:
db.define_table('tablename',
Field( ....
....
....
Field('created_on','datetime', default=request.now, writable=False),
Field('last_modified','datetime', default=request.now, update=request.now),
)
Then when I request the data, I set the orderby attribute to last_modified:
rows = db().select(db.tablename.ALL, orderby=db.tablename.last_modified)
Then, I pass the results onto a Json dictionary object. Like so:
I'm passing them into a JSON dictionary object.Like so:
d = { r.index_id : {'index_id':r.index_id,
....
....
'comments':r.comments,
'created_on':r.created_on,
'last_modified':r.last_modified}
for r in rows}
return response.json(dict(entry_dict=d))
When I get the response from the server, I return the dict to my ractive object.
MAIN.set('data_entries', data['entry_dict']);
Then, I render the results in ractive:
{% #data_entries:index_id%}
<tr class = "datarow" onclick="window.document.location='{% url+ '/'+ index_id %}';">
<td>{% index_id %}</td>
....
<td>{% last_modified %}</td>
</tr>
{% /data_entries %}
However, when the data is returned to the webapp, I get to following:
Am I doing this right?
In Python, dictionaries do not preserve order, so when you convert the d dictionary to JSON, you will not necessarily get the keys in the order of the original Rows object. You could instead use an OrderedDict, but it doesn't appear you really need a dictionary anyway -- just create a list (using the as_list method):
return response.json(dict(entry_dict=rows.as_list()))
Then in Ractive, change:
{% #data_entries:index_id %}
to:
{% #data_entries %}
It doesn't appear you need the index value within each loop. Instead, you will be able to access the index_id field of each record as part of the data context of the section.

In Flask: When using wtforms, SQLAlchemy, getting "OperationalError: (sqlite3.OperationalError) no such table:" when the table exists

I've got a pretty basic flask application in the works and I am having a problem with saving data to a sqlite database and table that most definitely exist and does take form submissions if I use a direct execute() method like so:
def get_db():
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
...
gdb = get_db()
gdb.execute("insert into term (term_txt) values (?)", (form.term_txt.data,))
gdb.commit()
The model for which is:
class Term(db.Model):
id = db.Column(db.Integer, primary_key=True)
term_txt = db.Column(db.String(255), unique=True)
def __init__(self, term_txt):
self.term_txt = term_txt
def __repr__(self):
return '<Term %r>' % self.term_txt
The form is:
{% extends "layout.html" %}
{% block body %}
<form action="{{ url_for('addTerm') }}" method="POST">
{{ form.term_txt }}
{{ form.csrf_token }}
<p><input type="submit" label="Add Term"></p>
</form>
{% endblock %}
But if I try to use the Flask suggested way of doing it as in this route, i get the following error OperationalError: (sqlite3.OperationalError) no such table: term [SQL: u'INSERT INTO term (term_txt) VALUES (?)'] [parameters: (u'my test term',)]:
#app.route('/add_term', methods=('GET', 'POST'))
def addTerm():
form = AddTermForm(csrf_enabled=True)
if request.method == "POST":
newTerm = Term(term_txt=form.term_txt.data)
db.session.add(newTerm)
db.session.commit()
#gdb = get_db()
#gdb.execute("insert into term (term_txt) values (?)", (form.term_txt.data,))
#gdb.commit()
return redirect(url_for('terms'))
else:
return render_template('new_term.html', form=form)
db comes from:
app = Flask(__name__)
app.config.from_envvar('FLASKAPP_SETTINGS', silent=True)
db = SQLAlchemy(app)
As mentioned, the database exists and I can save from the form to the database if I use the above sql command in the code, but I don't feel like that's the best approach.
Also I don't know if the sql command should be in the error or not, maybe something is wrong there. Otherwise, I can't figure out why this isn't working as it appears across a number of docs that this is the way to do it.
For me it looks like the database for SQLAlchemy was configured incorrectly. The db had been created without SQLAlchemy. Following this made it work: How do you set up a Flask application with SQLAlchemy for testing?

Create a last visited list with Symfony & Twig

I want to create a “last visited pages” list with Symfony and Twig.
For that purpose I wrote a history service which saves the last visited routes in the session.
But I just have the route name no alias for the user experience.
So the route country_info should hold a string like “Country Information”.
Is it possible to define a alias in the routing.yml?
No, it's not possible to define route aliases in routing.yml. The routing system is not meant to do that.
If you have a fixed number of pages you could just read the session values in your Controller and translate each route name in order to print it with Twig later.
Supposing you are storing last visited pages routes in an array, you can try the following:
In your Controller action:
// Read session
$page_routes = $session->get('last_visited_routes_array');
$output_array=array();
foreach ($page_routes as $route){
// Translate route to name
switch($route){
case "country_info":
$output_array['country_info'] = "Country Information";
break;
// ... Add more Cases here ...
}
}
// Return generated array so it can be used by Twig
return array('output_array' => $output_array);
In your Twig template:
{% for page_route, page_name in output_array %}
{{page_name}}
{% endfor %}
Hope it helps.

Resources