Commit 92da1296 by Raphael Mäder

Merge branch 'cleanup-temlplate-helper' into 'master'

Cleanup temlplate helper See merge request !348
parents d7670efd 029770b2
@import org.apache.commons.lang3.StringUtils
@import ch.insign.commons.search._
@import ch.insign.cms.views.html._
@(
data: ch.insign.cms.blocks.searchresultblock.SearchResultBlock,
query: String,
results: List[ch.insign.commons.search.SearchResult])
@import play.mvc.Controller
@import ch.insign.commons.search._
@import ch.insign.cms.views.html._
@import ch.insign.cms.models._
@import play.api.i18n.Messages;
results: List[ch.insign.commons.search.SearchResult]
)
@contentBlockForSearchBlock(data = data){
<p>
@if(Template.nonEmpty(query)){
@Messages("searchresult.searchfor", query, String.valueOf(results.size))
}else{
@Messages("searchresult.noquery")
}
@Option(query).filter(_.nonEmpty).map { q =>
@Messages("searchresult.searchfor", q, results.size)
}.getOrElse {
@Messages("searchresult.noquery")
}
</p>
<ol>
@for(result <- results){
@for(result <- results) {
<li>
<a href="@result.getUrl">@Template.nonEmpty(result.getTitle, result.getUrl)</a>
<br />@Template.html(result.getSnippet)
<a href="@result.getUrl">@Seq(result.getTitle, result.getUrl).filter(StringUtils.isNotBlank(_)).headOption</a>
<br />@Html(result.getSnippet)
</li>
}
</ol>
......
......@@ -37,7 +37,7 @@
}
@if(isNonEmpty(data.getText)) {
<p class="lead slider-text">@Template.html(data.getText)</p>
<p class="lead slider-text">@Html(data.getText.get)</p>
}
@if(isNonEmpty(data.getLink) && isNonEmpty(data.getLinkText)) {
......
......@@ -312,10 +312,14 @@ public class FrontendController extends Controller {
StringBuilder sb = new StringBuilder();
sb.append("<html>\n<body>\n");
sb.append(String.valueOf(results.size())).append(" results found for '").append(keywords).append("'<br><br>\n");
sb.append(results.size()).append(" results found for '").append(keywords).append("'<br><br>\n");
for (SearchResult result : results) {
sb.append("<p>\n");
sb.append(String.format("<a href='%s'>%s</a>\n", result.getUrl(), Template.nonEmpty(result.getTitle(), result.getUrl(), "...")));
sb.append(String.format("<a href='%s'>%s</a>\n",
result.getUrl(),
Stream.of(result.getTitle(), result.getUrl(), "...")
.filter(StringUtils::isNotBlank)
.head()));
sb.append("<br />\n...");
sb.append(result.getSnippet());
sb.append("...</p>\n");
......
......@@ -220,10 +220,10 @@ public class DefaultBootstrapper implements Bootstrapper {
page3.getPageTitle().set("en", "Page 2.1");
// Add a sub block to the main pane collection
CollectionBlock mainPane = (CollectionBlock) Template.addBlockToSlot(CollectionBlock.class, homepage, "main");
CollectionBlock mainPane = Template.addBlockToSlot(CollectionBlock.class, homepage, "main");
ContentBlock block, block2, block3, block4;
try {
block = (ContentBlock)mainPane.addSubBlock(ContentBlock.class);
block = mainPane.addSubBlock(ContentBlock.class);
block.getTitle().set("en", "Play! CMS");
block.getContent().set("en", "The insign Play CMS is meant as a solid platform for custom Play projects " +
"that require solid cms features at their base. Play CMS does not try to be a full-fledged major " +
......@@ -231,7 +231,7 @@ public class DefaultBootstrapper implements Bootstrapper {
"requirements on content editing.");
block.save();
block2 = (ContentBlock)mainPane.addSubBlock(ContentBlock.class);
block2 = mainPane.addSubBlock(ContentBlock.class);
block2.getTitle().set("en", "Search");
block2.getContent().set("en", "<p>The CMS offers a flexible interface for fulltext searching. " +
"Implementing projects and define their own SearchProviders, or use an existing one " +
......@@ -239,14 +239,14 @@ public class DefaultBootstrapper implements Bootstrapper {
"<a href=\"https://confluence.insign.ch/display/PLAY/Search\">Learn more about search</a>.</p>");
block2.save();
block3 = (ContentBlock)mainPane.addSubBlock(ContentBlock.class);
block3 = mainPane.addSubBlock(ContentBlock.class);
block3.getTitle().set("en", "Caching");
block3.getContent().set("en", "Play-CMS supports powerful " +
"<a href=\"https://confluence.insign.ch/display/PLAY/Caching\">caching mechanisms</a> at the block level. " +
"Caching is disabled by default, it can be enabled globally via configuration and refined per block class.");
block3.save();
block4 = (ContentBlock)mainPane.addSubBlock(ContentBlock.class);
block4 = mainPane.addSubBlock(ContentBlock.class);
block4.getTitle().set("en", "Play Auth");
block4.getContent().set("en", "<p>The insign <a href=\"https://confluence.insign.ch/display/PLAY/Play+Auth\">Play Auth</a> " +
"provides functionality to manage essential information about parties (people and organizations) and " +
......@@ -259,10 +259,10 @@ public class DefaultBootstrapper implements Bootstrapper {
}
// Add a sub block to the sidebar collection
CollectionBlock sidebarPane = (CollectionBlock) Template.addBlockToSlot(CollectionBlock.class, homepage, "sidebar");
CollectionBlock sidebarPane = Template.addBlockToSlot(CollectionBlock.class, homepage, "sidebar");
ContentBlock sidebarBlock;
try {
sidebarBlock = (ContentBlock)sidebarPane.addSubBlock(ContentBlock.class);
sidebarBlock = sidebarPane.addSubBlock(ContentBlock.class);
sidebarBlock.getTitle().set("en", "Multi-language");
sidebarBlock.getContent().set("en", "The cms is " +
"<a href=\"https://confluence.insign.ch/display/PLAY/Languages\">multi-language capable</a>. " +
......@@ -290,7 +290,7 @@ public class DefaultBootstrapper implements Bootstrapper {
}
try {
SliderEntryBlock slide1 = (SliderEntryBlock)sliderCollection.addSubBlock(SliderEntryBlock.class);
SliderEntryBlock slide1 = sliderCollection.addSubBlock(SliderEntryBlock.class);
slide1.setSite(site.key);
slide1.getTitle().set("en", "Play! CMS");
slide1.getText().set("en", "The Play Framework 2 CMS");
......
......@@ -39,6 +39,7 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.*;
import java.util.*;
import java.util.stream.Stream;
@Entity
@Table(name = "cms_block_page")
......@@ -427,7 +428,15 @@ public class PageBlock extends AbstractBlock implements Page {
}
public String toString() {
return String.format(getClass().getSimpleName() + " (id: %s, title: %s, key: %s)", getId(), Template.nonEmpty(getPageTitle(), getNavTitle()), getKey());
return String.format(
getClass().getSimpleName() + " (id: %s, title: %s, key: %s)",
getId(),
Stream.of(getPageTitle(), getNavTitle())
.map(MString::get)
.filter(StringUtils::isNotBlank)
.findFirst()
.orElse(""),
getKey());
}
/**
......
......@@ -20,10 +20,8 @@ import ch.insign.cms.blocks.ResponsiveBlock;
import ch.insign.cms.blocks.ResponsiveCollection;
import ch.insign.cms.blocks.backendlinkblock.BackendLinkBlock;
import ch.insign.cms.blocks.backendlinkblock.BackendMenuItem;
import ch.insign.cms.blocks.horizontalcollection.HorizontalCollectionBlock;
import ch.insign.cms.permissions.BlockPermission;
import ch.insign.cms.blocks.groupingblock.GroupingBlock;
import ch.insign.commons.db.MString;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
......@@ -39,7 +37,6 @@ import play.mvc.Controller;
import play.mvc.Http;
import java.util.*;
import java.util.stream.Collectors;
/**
* This is a helper class for templates to work with cms objects.
......@@ -57,21 +54,17 @@ public class Template {
* @param slot
* @return block
*/
public static AbstractBlock addBlockToSlot(Class<? extends AbstractBlock> blockClass, AbstractBlock parentBlock, String slot) {
AbstractBlock newBlock = AbstractBlock.find.byParentAndSlot(parentBlock, slot);
if (parentBlock == null) {
throw new RuntimeException("Cannot add new block to slot: Parent is null!");
}
public static <T extends AbstractBlock> T addBlockToSlot(Class<T> blockClass, AbstractBlock parentBlock, String slot) {
Objects.requireNonNull(parentBlock, "Cannot add new block to slot: Parent is null!");
T newBlock = (T) AbstractBlock.find.byParentAndSlot(parentBlock, slot);
if (newBlock == null) {
try {
logger.info("Creating a new " + blockClass.getSimpleName() + " for parent " + parentBlock.getId() + " and slot " + slot);
logger.info("Creating a new {} for parent {} and slot {}", blockClass.getSimpleName(), parentBlock.getId(), slot);
newBlock = blockClass.newInstance();
} catch (Exception e) {
logger.error("Could not instantiate new block of type: " + blockClass.getName(), e);
logger.error("Could not instantiate new block of type: {}", blockClass.getName(), e);
e.printStackTrace();
}
newBlock.setSlot(slot);
......@@ -85,9 +78,6 @@ public class Template {
// Fixes JPA constraint violation error when trying to delete
// a page block with just initialized slots on that page
JPA.em().getEntityManagerFactory().getCache().evict(parentBlock.getClass(), parentBlock.getId());
} else {
logger.debug("Adding existing " + blockClass.getName() + " for parent " + parentBlock.getId() + " and slot " + slot);
}
return newBlock;
......@@ -100,11 +90,11 @@ public class Template {
* @param key
* @return the block
*/
public static AbstractBlock addBlockByKey(Class<? extends AbstractBlock> blockClass, String key) {
AbstractBlock newBlock = AbstractBlock.find.byKey(key);
public static <T extends AbstractBlock> T addBlockByKey(Class<T> blockClass, String key) {
T newBlock = (T) AbstractBlock.find.byKey(key);
if (newBlock == null) {
logger.info("Creating a new " + blockClass.getName() + " with key " + key);
logger.info("Creating a new {} with key {}", blockClass.getName(), key);
try {
newBlock = blockClass.newInstance();
......@@ -114,12 +104,10 @@ public class Template {
newBlock.save();
} catch (Exception e) {
logger.error("Could not create new block of type: " + blockClass.getName(), e);
logger.error("Could not create new block of type: {}", blockClass.getName(), e);
e.printStackTrace();
}
} else {
logger.debug("Adding existing " + blockClass.getName() + " with key " + key);
}
return newBlock;
......@@ -151,52 +139,6 @@ public class Template {
}
/**
* Add the data as html to the template (tags are then rendered, not escaped)
* @param input
* @return html
*/
public static Html html(String input) {
if (input == null) {
input = "";
}
return Html.apply(input);
}
/**
* Add the data as html to the template (tags are then rendered, not escaped)
* @param input
* @return html
*/
public static Html html(MString input) {
if (input == null) {
return Html.apply("");
} else {
return Html.apply(input.get());
}
}
/**
* Return the first not null, not empty string.
* Returns "" if none was found.
*/
public static String nonEmpty(Object... args) {
for (int i = 0; i < args.length; i++) {
if (args[i] != null && !args[i].toString().equals("")) {
return args[i].toString();
}
}
return "";
}
/**
* Returns whether obj is an instance of clazz
*/
public static boolean isInstanceOf(Object obj, Class clazz) {
return clazz.isInstance(obj);
}
/**
* Filter a block list and return only those that should be shown
* to the current user (applying time- and right restrictions
* and for pages also nav item visible flag checks)
......@@ -237,7 +179,7 @@ public class Template {
/**
* Get the time restriction state of a block.
*/
public static TR hasTimeRestriction (AbstractBlock block) {
public static TR hasTimeRestriction(AbstractBlock block) {
Date now = new Date();
Date from = block.getDisplayFrom();
......@@ -259,7 +201,7 @@ public class Template {
* Returns {@code true} if {@code block} is NOT accessible for unauthenticated users
* and users without {@code AbstractBlock.PERMISSION_READ} permission.
*/
public static boolean hasAccessRestriction (AbstractBlock block) {
public static boolean hasAccessRestriction(AbstractBlock block) {
return PlayAuth.isRestricted(BlockPermission.READ, block);
}
......@@ -269,21 +211,11 @@ public class Template {
* Non-page-items have no visible flag thus are always considered visible.
*/
public static boolean isVisible(AbstractBlock block) {
if (block instanceof PageBlock) {
return ((PageBlock) block).isVisible();
}
return true;
}
/**
* Converts any collection of String to a sorted list
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends Comparable> List<T> asSortedList(Collection<T> collection) {
T[] array = collection.toArray((T[]) new Comparable[collection.size()]);
Arrays.sort(array);
return Arrays.asList(array);
return true;
}
/**
......@@ -330,20 +262,6 @@ public class Template {
}
/**
* Returns the default edit bar for pages if the page is a cms page (and an empty string otherwise)
* Can be used in main layout templates to place the page-level edit bar outside / on top of the page template.
* @param page either a PageBlock (shows the edit bar) or a Page instance (does not show the edit bar since it's no cms page then)
*/
public static Html editBar(Page page) {
if (page instanceof AbstractBlock) {
// Unfortunately play does not generate a render() method for mandatory params only..
return ch.insign.cms.views.html._blockBase.render((AbstractBlock) page, true, true, true, false, "", "", false, "", Html.apply(""));
} else {
return Html.apply("");
}
}
/**
* Used from _blockBase: Tries to return the block template's class name (via stacktrace).
* Important: Use this for debugging purpose only (it's an expensive call)
* @return Class name the method calling the method where this call is placed
......
......@@ -73,7 +73,7 @@
<div class="checkout_container">
<div class="row" id="template-@emailTemplate.getId">
<div class="col-md-12">
@Template.html(emailTemplate.getContent.get(lang))
@Html(emailTemplate.getContent.get(lang))
</div>
</div>
</div>
......
......@@ -19,14 +19,14 @@
case Template.TR.NONE => {}
}
@if(Template.isInstanceOf(subPage, classOf[GroupingBlock])){<b>}
@subPage.getNavTitle
@if(Template.isInstanceOf(subPage, classOf[GroupingBlock])){</b>}
@if(subPage.isInstanceOf[GroupingBlock]){<b>}
@subPage.getNavTitle
@if(subPage.isInstanceOf[GroupingBlock]){</b>}
@if(subPage.getKey!=null){<span class="text-muted">[@subPage.getKey]</span>}
</div>
<div class="nestable-list-actions">
@if(!Template.isInstanceOf(subPage, classOf[GroupingBlock])) {
@if(!subPage.isInstanceOf[GroupingBlock]) {
@if(subPage.canRead) {
<a href="@subPage.getNavItem.getURL" target="_blank" title="@Messages("cms.navigation.entry.show")">
<i class="fa fa-eye"></i>
......
......@@ -16,17 +16,14 @@
package ch.insign.commons.search;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/**
* Search results interface
*/
public interface SearchResult {
public String getTitle();
public String getSnippet();
public String getUrl();
public String getImage();
public String getAuthor();
public String getLanguage();
String getTitle();
String getSnippet();
String getUrl();
String getImage();
String getAuthor();
String getLanguage();
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment