Django_table2 TemplateColumn usage - django-tables2

I just read the folowing article and i would like more information about the first method using TemplateColumn. I would like to produce two pseudo columns for edit and delete methods of each record.
edit.html
> <a href="{% url some_url_edit record.pk %}" class="tbl_icon
> edit">Edit</a>
delete.html
> <a href="{% url some_url_del record.pk %}" class="tbl_icon
> delete">Delete</a>
2 pseudo columns that does not exist in DB
class MyTable(tables.Table):
column_edit = tables.TemplateColumn(edit.html)
column_delete=tables.TemplateColumn(delete.html)
If that is correct according to the article how record.pk is passed on every template to get the required information about its key?

If you want to edit or delete an object then you'd need to use a model table:
class MyModelTable(tables.Table):
name = tables.columns.Column()
edit = tables.TemplateColumn('<a href='{% url "edit_my_model_instance" record.id %}'>Edit</a>', verbose_name=u'Edit', )
delete = tables.TemplateColumn('<a href='{% url "del_my_model_instance" record.id %}'>Delete</a>', verbose_name=u'Delete', )
class Meta:
model = models.MyModel
Notice how we use record.id to pass it the id of each row to the url template tag in order to output the correct edit/delete url.

i am afraid that your code is a bit faulty as someone must use the following commands to get properly displayed the images inside the columns:
edit = tables.TemplateColumn('<img src=\'{% load staticfiles %} {% static "images/edit.jpg" %}\' / width="25">',verbose_name=u'Edit',)
delete = tables.TemplateColumn('<img src=\'{% load staticfiles %} {% static "images/delete.jpg" %}\' / width="25">',verbose_name=u'Delete',)
I would like to ask if i could use inside tables.py bootstrap css for better rendering of columns and data tables?

Related

Get the domain name in Twig/Timber to output in WordPress?

When I have an error in my custom WordPress theme I would like to output the webmaster email address which would be webmaster#mydomainname.com but I am a bit baffled on how to do this in Twig/Timber in the most straightforward way: <p class="text-danger fw-bold">PAGE ERROR - Please contact Webmaster at webmaster#{{ #notsure# }}</p>
webmaster#{{ site.url }} just outputs: webmaster#https://mywordpress.local which obviously won't work.
UPDATED: To get by I am using webmaster#{{ site.url[8 :] }} as that strips away the https:// and outputs webmaster#mywordpress.local but seems there should be a cleaner way somehow?
There are two ways to do this:
You can use Advanced custom field. Make a email field and then print that value inside the twig file. Inside advanced custom field, you can add any email you have no need to extract a domain name. For more information follow this reference: https://timber.github.io/docs/guides/acf-cookbook/
Second method is the way you doing is correct but you need to split domain name from site.url using slice method:
{% set website = "https://mywordpress.local" %} //
//calcualting length of string
{% set lengthOfWebsite = website|length %}
//using length here to split the string accordingly. 8is for split "https://" from actual domain name.
{% set domainName = website|slice(8,lengthOfWebsite) %}
webmaster#{{domainName}}
For the first line of code in your case will be:
{% set website = site.url %}
For the last line
webmaster#{{domainName}}
can also be replaced by:
{% set actualDomainName = 'webmaster#' ~ domainName %}
{{actualDomainName}}

How to add a static content in a specific drupal page something like like using {% if is_front %} {% endif %} to add it in the home page

I am new to drupal and I tried to add a simple image as static in the html.html.twig page.
To display this image in the home page only I added this condition
{% if is_front %}
{% endif %}
What is the condition to add it in another specific page example /contact/
I tried this code inside the page but it does not work, should I wrap it with some codes?
if(drupal_valid_path('contacts') == 1) //this exists
{
print_r('Exists!');
}
Please help! Many thanks.
Your question is mixing twig with a drupal 7 function. I suppose anyway you're on D8/D9.
I also suppose the "contacts" page is a node. If it is somethings else - e.g. a view page - instead of checking for the node, you may have to check the route.
There are various approach, two possible would be:
A hook preprocess where you load the node if exists
function hook_preprocess_html(&$variables) {
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
$variables['node'] = $node;
}
}
And the in the twig check the id of the node is the right one
override the html.html.twig for the specific node, e.g. html--node--10.html.twig. In this case I'd suggest not to duplicate all the content of the base html.html.twig, but to use the embed tag to override only the appropriate block.

how to only show number with truncate or css

I want to display S1 only instead of season 1. Thus I need to truncate season and put only 1 and add "S" at the front.
<a href="{% url 'season_detail' slug=all_episode.season.slug %}">
{{ all_episode.season}}
</a>
How do I truncate the word "season"?
Edit:
Here's what I did again
I created templatetag folder inside my app
then added init.py and seasonify.py
and inside seasonify.py I added
from django import template
register = template.Library()
#register.filter
def seasonify(value):
return value.replace('season', 'S')
then inside my template
I added
{% load seasonify %}
and {% episode.season|seasonify %}
Your best bet is to write a custom template filter. The logic is simple:
#register.filter
def seasonify(value):
return value.replace('season', 'S')
then simply use it in your templates:
{{ all_episode.season | seasonify }}
See Django docs for details on where to put this code.

Adding own action to SonataAdminBundle dropdown menu

We use the SonataAdminBundle with our Symfony2 application. When editing an entity I want to add an own action to the dropdown menu which is located in the top right corner, but I have no idea how this works.
I know I can add own routes via configureRoutes(RouteCollection $collection) and how to add batch actions or add own actions behind entities in the list view, but how can I add an own link in the actions dropdown in the edit view?
It is basically just a link like "Show me this entity in the frontend", so no big logic is needed.
One way would be to override the template that is used when editing. Now, what you need to do is:
Create new directory (if you already haven't) in app/Resources called SonataAdminBundle. Inside, create another one called views. This would create a path like app/Resources/SonataAdminBundle/views. This is Symfony basic template overriding. You can read more on that subject here.
Now, you should copy the original template following the same path as it is, inside the original bundle. The template file we are interested here is located in sonata-project/admin-bundle/Resources/views/CRUD/base_edit.html.twig. This means that you have to create another folder inside views (the one we just created in app, called CRUD. So, now we have to following path app/Resources/SonataAdminBundle/views/CRUD. Paste the template (base_edit.html.twig) inside and we can start editing.
Keep in mind that the following template is used in every edit action you have. So it's up to you whether you want to display that link in every edit_action or not. I will show you 1 way to limit that for specific action.
The block you gonna edit is {% block actions %} which is responsible for rendering the dropdown. This is how it should look now:
{% block actions %}
<li>{% include 'SonataAdminBundle:Button:show_button.html.twig' %}</li>
<li>{% include 'SonataAdminBundle:Button:history_button.html.twig' %}</li>
<li>{% include 'SonataAdminBundle:Button:acl_button.html.twig' %}</li>
<li>{% include 'SonataAdminBundle:Button:list_button.html.twig' %}</li>
<li>{% include 'SonataAdminBundle:Button:create_button.html.twig' %}</li>
{% endblock %}
Now all that's left to do is insert your link after last <li> tag.
{% if admin.id(object) is not null and app.request.get('_route') == 'my_route' %}
<li>
View in Frontend
</li>
{% endif %}
admin.id(object) will return the current ID of the item you edit. app.request.get('_route') will return the route of your edit action. You can remove that if you want your link to be displayed in all edit actions. Change View in Frontend with your route name using admin.id(object) and you should be good to go.
In your admin class, override the following method:
public function getActionButtons($action, $object = null)
{
$list = parent::getActionButtons($action, $object);
$list['upload'] = [
'template' => ':admin:my_upload_button.html.twig',
];
return $list;
}
This will add a custom action button on all the pages of this admin. You can add any logic in here to decide which pages ($action-s) you want to display the button on.
You can do what you want in the template, but just to complete my example and show the connection with my custom action:
<li>
<a class="sonata-action-element" href="{{ admin.generateUrl('upload') }}">
<i class="fa fa-cloud-upload" aria-hidden="true"></i>
Upload stuff
</a>
</li>
Another way would be to override the method generateObjectUrl() in your object's admin class.
/**
* #see \Sonata\AdminBundle\Admin\Admin::generateObjectUrl()
*/
public function generateObjectUrl($name, $object, array $parameters = array(), $absolute = false)
{
if ('show' == $name) {
return $this->getRouteGenerator()->generate('your_route_to_public_facing_view', [
'id' => $this->getUrlsafeIdentifier($object),
], $absolute );
}
$parameters['id'] = $this->getUrlsafeIdentifier($object);
return $this->generateUrl($name, $parameters, $absolute);
}
And that's it. No mucking with templates. And no template code that will run on every other admin.
To get the link to appear automatically, you will have to add something to the $showMapper via configureShowFields(). (If anyone knows a better way, please do tell.)
Overriding generateObjectUrl() has another bonus: If you display a show button on the $listMapper, the URL there will be updated there as well.
Edited to say: since this overrides the show route, you will no longer be able to use that built-in feature. That's ok for me since I need to view my object with all the front-end css and js loaded.

How to get the current page name in Silex

I'm wondering how to get the current page name, basically 'just' the last parameter in the route (i.e. /news or /about). I'm doing this because I want to be able to have the current page in the navigation highlighted.
Ideally, I'd like to store the current page name in a global variable so that in Twig I can just compare the current page name against the link and add a class accordingly.
I can't figure out how to add the current page name to a global variable though. I've tried using something like this:
$app['twig']->addGlobal('current_page_name', $app['request']->getRequestUri());
at the top of my app.php file, but an 'outside of request scope' error. But I wouldn't like to have to include this in every route.
What's the best way to do this?
If you put it into an app-level before middleware like this, that'll work:
$app->before(function (Request $request) use ($app) {
$app['twig']->addGlobal('current_page_name', $request->getRequestUri());
});
The "page name" part of your question is unclear, are you looking for the current route's name? You can access that via $request->get("_route") even in the before middleware, as it gets called when routing is already done.
You could also generate navigation list directly in stand alone nav twig template. And then import it in to the main template. Then you would only have to get silex to pass to the view the current page identifier. Simplest way... for example from Silex you would have to pass in the "path" variable to your view. Probably it would more convenient to to fetch nav_list from database and pass it in to twig template as global array variable instead. However this example is the simplest you could get to do what you intend.
nav.twig
{% set nav_list = [
["./", "home"],
["./contact", "contact"],
["./about", "about us"]
{# ... #}
] %}
{% set link_active = path|default("") %}
{% for link in nav_list %}
<li><a href="{{ link[0] }}" class="{% if link[0] == link_active %} activeClass {% endif %}" >{{ link[1] }}</a></li>
{% endfor %}
app.php
//...
$app->match('/about', function (Request $request) use ($app) {
return $app['twig']->render('about.twig', array(
'path' => './'.end(explode('/', $request->getRequestUri()))
));
});
//...

Resources