knackforge
September 16, 2015
I recently had a problem with views_embed_view function while embedding certain views in the template file. In some cases a view might be empty, i.e., may not have any results.
In my case, I embedded some views in the template file and had certain styles for the div that wrapped the view. These styles should be displayed only if the view was not empty. I checked if the view was empty or not, then only rendered the wrapping div along with the view in the template file. But what I witnessed was not what I expected. Though the view was empty, the styling was displayed along with the wrapping div. Later I found that views_embed_view function returns the following markup even when the view is empty.
<div class="view view-kf-content view-id-kf_content view-display-id-block view-dom-id-sd2db2bfcdh546hfddfba7ad95sdff32"> </div>
To overcome this problem, I came up with a custom function that will return the result (only if exists)
function kf_embed_views($view_name, $display, $arg1 = FALSE) { $output = ''; $view = views_get_view($view_name, $display, $arg1); $view->set_display($display); $view->args = array($arg1); $view->pre_execute(); $view->execute(); if ($view->result) { $output = $view->preview($display); } return $output; }
I had to embed many views in many template files, so I just passed the view name, display id, and argument to this custom function and used it wherever I wanted. You can add more arguments if you need.
Just like how your fellow techies do.
We'd love to talk about how we can work together
Take control of your AWS cloud costs that enables you to grow!