Wagtail: Rendering tags from Fieldblock - tags

I am really stuck on this: (sorry, newbie problems)
Following the method exposed in this post I need to render the tags in a page, but I am not able to get the tag values through the #property
The code is as follow, the models:
class TagsBlock(blocks.FieldBlock):
"""
Basic Stream Block that will use the Wagtail tags system.
Stores the tags as simple strings only.
"""
def __init__(self, required=False, help_text=None, **kwargs):
# note - required=False is important if you are adding this tag to an existing streamfield
self.field = forms.CharField(widget=AdminTagWidget, required=False)
super().__init__(**kwargs)
class ServicesPage(Page):
services = StreamField([
('services',blocks.StructBlock([
('entries',PortfolioBlock()),
('tags',TagsBlock(required=False)),
]))], null=True, blank=True)
#property
def get_tags(self):
"""
Helpful property to pull out the tags saved inside the struct value
Important: makes some hard assumptions about the names & structure
Does not get the id of the tag, only the strings as a list
"""
tags_all = [block.value.entries.get('tags', '').split(',') for block in self]
tags = list(chain.from_iterable(tags_all))
return tags
content_panels = Page.content_panels + [
StreamFieldPanel('services'),
]
Then in the template im just doing:
<div class="row-4">
{% for tag in page.services.get_tags %}
{{tag}}
{% endfor %}
</div>
However, I can't get any result. I have really tried everything, but I can't figure how to call the property to give me the list of values.
Thank you very much in advance for your time,
Francisco

In your template, the line
{% for tag in page.services.get_tags %}
would be trying to access a property named get_tags on the 'services' field of the page. However, get_tags isn't defined there - it's defined as a property of the page object - so this line should be
{% for tag in page.get_tags %}
Secondly, in the line
tags_all = [block.value.entries.get('tags', '').split(',') for block in self]
you're intending to loop over all the items in the StreamField, but the self in for block in self refers to the page object. This should be for block in self.services.
Finally, in the same line, block.value will give you the value of each block, which in this case will be a dictionary of two items, entries and tags. If you wanted to access entries (the PortfolioBlock), you would write block.value['entries'] or block.value.get('entries') rather than block.value.entries - but really you don't want that, you want to access the tags item instead - so block.value.entries.get('tags', '').split(',') should be block.value.get('tags', '').split(',').

Related

FlaskWTF same form on every view / page

in my Flask Project i have configured a basepage.html Jinja template every other page inherits from.
In this basepage.html i want to have a Search bar at the top, so that it also appears at every page inheriting from it.
The input from this search form (is a form even the best way to do it?) should be processed
by the routing function search() I defined as follows:
views.py
#app.route('/')
#app.route('/dashboard')
def dashboard():
return render_template('Dashboard.html') #Dashboard.html inherits from basepage.html
#app.route('/search', methods=['GET' ,'POST'])
def search():
search_query = #input from search-bar
result = #get data matching search_query from database
return render_template('Search.html', results = results) #Search.html extends basepage.html
forms.py excerpt:
class Search(FlaskForm):
search_query = StringField('Search for ...')
submit = SubmitField('Search')
Is there a way i can have my Search form on every page, so when i enter my query in the bar at the top of the Dashboard form and press enter the search_query gets processed by the search() view?
Just create your searchbar template code in a partial file located at /templates/includes/my_searchbar.html or whatever you want to name it and then in your base template just place an includes directive wherever you want the search to render in, something like:
{% include 'includes/my_searchbar.html' %}
If the searchbar is included in base and all your other templates inherit from base, then search will be included on all pages.
All of your routes will also need to have the Search() form class included so they have access to the form, so you will need to modify your routes something like:
from app.forms import Search #if you defined Search in /app/forms.py
#app.route('/dashboard')
def dashboard():
search_form = Search() #initialize an instance of the form
return render_template('Dashboard.html', search_form=search_form)
Then you can use search_form in your includes/my_searchbar.html partial to render the form. Maybe something like:
<form class="form" method="post" role="form">
{{ search_form.hidden_tag() }}
{{ search_form.search_query }}
{{ search_form.submit }}
</form>

View error in Flask when retrieving item in MongoDB

I am trying to populate a page built in Flask from items in MongoDB. My route looks like:
#app.route('/job/<posting>', methods=["GET"])
def job_post(posting):
posting = db.openings.find({'Id': posting})
title = db.openings.find_one({'Id': posting}, {'Title': 1, '_id':0})
return render_template('post_page.html', posting=posting, title=title)
My template page for post_page.html is:
{% extends "layout.html" %}
{% block content%}
<div class="container">
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<h3><a class="mr-2" href="#">{{ title }}</a></h3>
</div> -->
</article>
</div>
{% endblock content %}
When I attempt to access a page, I get an error saying "bson.errors.InvalidDocument: cannot encode object: <pymongo.cursor.Cursor object at 0x10dd402e8>, of type: <class 'pymongo.cursor.Cursor'>"
When I research that error, most of the issues have come from using find instead of find_one. I am using find_one here, and when I test it in a Python shell, the variable type for title is a dictionary, so I'm confused as to why it's passing a cursor object to the template.
You are passing posting in to the function and then immediately setting it in the first function posting = db.openings.find({'Id': posting}). I suspect you don't mean to do this.
find() return a cursor which you're then passing into the find_one() function which is causing the error you see.
Not sure what you are trying to achieve by calling find() then find_one() on the same collection. My suggestion is you remove the line posting = db.openings.find({'Id': posting})

How to access a method and pass an argument within the template?

In my template I want check whether an entity has a relation to another one. Meaning one object is in an attached Object Storage of another one.
In the controller I can simply call:
if ($product->getCategory()->offsetExists($category) {
print 'In category ' . $category->getName();
}
But I can't figure out the correct syntax in the template. I tried those without luck (both evaluate to true everytime):
<f:if condition="{product.category.offsetExists(category)}">true</f:if>
<f:if condition="{product.category.offsetExists({category})}">true</f:if>
Is this even possible within the template?
You can only access properties via Getter from Fluid with no parameters, but you can implement an own ViewHelper to check that. As parameters you can use your Product and the Category. Then you can call your ViewHelper from Fluid this way:
<vh:checkOffset product="{product}" category="{category}" />
or inline
{vh:checkOffset(product: product, category: category)}
Within your ViewHelper you can check this in the way you've done it in your Controller:
public function render($product, $category){
return ($product->getCategory()->offsetExists($category));
}
Additionally to sretuer's answer, I'll only mention that you can create VH which will display block conditionally like:
File typo3conf/ext/your_ext/ViewHelpers/CheckOffsetViewHelper.php
<?php
namespace VENDORNAME\YourExt\ViewHelpers;
class CheckOffsetViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
public function render() {
return ($product->getCategory()->offsetExists($category))
? $this->renderChildren()
: '';
}
}
?>
So you can use it in the view:
{namespace vh=VENDORNAME\YourExt\ViewHelpers}
<vh:checkOffset product="{product}" category="{category}" >
Display this only if product is in category
</vh:checkOffset>
Of course you need to fix VENDORNAME and YourExt according to your extension, can be found at the beginning of every controller, model, repository etc.
You may consider https://fluidtypo3.org/viewhelpers/vhs/master/Condition/Iterator/ContainsViewHelper.html which is designed for creating conditions in Fluid that check if an array or Iterator contains another object and works exactly like f:if regarding then and else arguments and f:then and f:else child nodes.

How to define a `separator` tag in play-1.x without modifing play's source code

I want to define a tag separator tag, which inside a list tag, can add separator between items.
The sample code is:
List<String> users = new ArrayList<String>();
users.add("Jeff");
users.add("Mike");
#{list users, as: 'user'}
#{separator ' + ' /}
<span>${user}</span>
#{/list}
If I don't use the separator tag, the code will be:
#{list users, as: 'user'}
${user_isFirst ? '' : ' + '}
<span>${user}</span>
#{/list}
The generated html code will be:
<span>Jeff</span> + <span>Mike</span>
I tried defined a fastTag:
public static void _separator(Map<?, ?> args, Closure body, PrintWriter out, GroovyTemplate.ExecutableTemplate template, int fromLine) {
Object value = args.get("arg");
// TODO how to get the value of `as` defined in parent `list` tag?
out.print(value);
}
But the problem is I can't get the value of as defined in list tag (which is user) in this case.
You can create a custom list tag in groovy like this
#{list items:_arg, as:'tmp'}
%{
attrs = [:]
attrs.put(_as, tmp)
}%
#{ifnot tmp_isFirst}${_sep}#{/ifnot}
#{doBody vars:attrs /}
#{/list}
and use it like this
#{myList users, as:'user', sep:','}
${user}
#{/myList}
You should trace into your FastTag implementation. I think you'll see all the variables in scope inside the args map. This is from memory - so, sorry if not.
That said, I think it might be simpler if you copy the Java code for #{list} and add a new parameter, like
#{list users, as: 'user', separator: '+' }
and handle the logic in there. It seems a bit cleaner too from a design point of view - if it is a separator, how come you can put it anywhere you like in the code (and why not put it in twice!).
A final option is to look at Groovy or Java collection operators. http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html

Pyrocms tag as parameter in another tag

I tried to use {{ page:slug }} as a parameter in my page to get the blog articles from the category of the same name. For example:
Pagename = About me
Slug = about-me
Then create a category with the same name and slugname in Blog with associated articles. Now in pagelayouts I thought I could create the following, but it doesn't seem to work. Does anyone know why not?
{{ blog:posts order-by="created_on" dir="asc" category="{{ page:slug }}" }}
<section class="title">
<h4>
{{ title }}
</h4>
</section>
<section class="item">
<p>{{ intro }}</p>
<p>Read more..</p>
</section>
{{ /blog:posts }}
Solved
I found the answer by asking it face to face to another developer. Since this is a templating language, it doesn't support functionality. It just reads pre-made variables. So I will have to solve this problem by creating another method in pages/plugins.php.
You don't need to try and embed a tag in a string, just pass the tag straight to the attribute.
{{ blog:posts order-by="created_on" dir="asc" category="{{ page:slug }}" }}
Should be:
{{ blog:posts order-by="created_on" dir="asc" category=page:slug }}
Easier than you thought ey?
This is how I solved it using PHP. The below edit checks if the page parameter from the {{ blog:posts }} tag is set. When it is, it grabs the last segment and uses it as category filter in the database query to retreive only those posts:
In system/cms/modules/blog/plugin.php look for the 'posts' function and add a parameter:
$page = $this->attribute('page');
Then use the following statement to check if the parameter has been set and then add a 'where' statement:
if($page) //check if page is set
{
$segment = end($this->uri->segment_array()); //get the last segment from the url
$this->db->where('blog_categories.slug', $segment); //use the segment as filter
}
Now you can create a page containing blog posts from which the categories refer to its pagename like for example: www.website.com/pagename/subpagename/subsubpagename/awesome then use this as pagelayout and it will load a list of blogposts that have 'awesome' as category:
<h3>{{ page:title }}</h3>
{{ blog:posts order-by="created_on" dir="asc" page="true" }}
<h4>{{ title }}</h4>
<p>
{{ intro }}</p>
<p>
Read more..</p>
{{ /blog:posts }}
Instead of using tags i have found a simple solution to avoid tags as much as we can. Here is it.
Instead of using tags call a view in plugin and pass the third parameter as TRUE so that it return string instead of loading view than do any kind of looping and conditional checking in the view as usuall as you do with php o course. No need to meet tags there. After that in plugin where you are calling this view simply return a single variable and use your variable in tags in the page to display content of view.
Here is an example
class Plugin_Home extends Plugin
{
function test()
{
$this->load->model('test/test_m');
$data['test'] = $this->test_m->index();
return $this->load->view('test/test_view',$data , TRUE);
}
}
And in the page you can call it like this
{{ Home:test }}
And get rid of tags for conditioning and looping