I'd like to add custom class in my drupal template, in header region, but it doesn't works.
<!-- BEGIN OUTPUT from 'themes/marinenat/templates/layout/page.html.twig' -->
<div class="layout-container">
<header role="banner">
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'region' -->
<!-- FILE NAME SUGGESTIONS:
x region--header.html.twig
* region.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/marinenat/templates/layout/region--header.html.twig' -->
<div class="nav">
I'd like to add this class after "nav" class di region--header.
Anyone can help me
You already have all you need in the output.
Many roads lead to Rome
If themes/marineat is you base theme, simply copy themes/marinenat/templates/layout/region--header.html.twig into your subtheme's themes/MYSUBTHEME/templates directory and edit this file. Flush cache. Done.
If themes/marinenat is you custom subtheme simply edit the suggested template file /themes/marinenat/templates/layout/region--header.html.twig/ and add your class there. Flush cache. Done.
Last but not least you can also add classes to a region from a preprocess function from your MYSUBTHEME.theme file or any MYMODULE.module file.
/**
* Implements template_preprocess_region().
*/
function MYTHEME/MYMODULE_preprocess_region(&$variables) {
if (isset($variables['region']) && $variables['region'] == 'header') {
$variables['attributes']['class'][] = 'MYCLASS';
}
}
How to pass a string from PHP to Twig
/**
* Implements template_preprocess_region().
*/
function MYTHEME/MYMODULE_preprocess_region(&$variables) {
$variables['foo'] = FALSE;
if (isset($variables['region']) && $variables['region'] == 'header') {
// Get the current node.
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
// Get the node type.
$node_type = $node->bundle();
// Do what ever else you need to do to retrieve your class dynamically.
$variables['foo'] = $node_type;
}
}
}
Then in your region--header.html.twig Twig file it's:
{% if foo %}
<div class="nav {{ foo }}">
{{ content }}
</div>
{% endif %}
Related
I am trying to call multiple components into a page in the same line
in the index.js file, it is importing the components and exporting them
import Header from "./Header/Header";
import Navbar from "./Navbar/Navbar";
const exportedObject = {
Header,
Navbar,
};
export default exportedObject;
and adding the imports to the page
import { Header, Navbar } from "../components";
<div>
<Header title="about page" />
<Navbar />
<h1>About</h1>
<p>THIS is the about page</p>
</div>
I keep getting this error
Error: Element type is invalid: expected a string (for built-in
components) or a class/function (for composite components) but got:
undefined. You likely forgot to export your component from the file
it's defined in, or you might have mixed up default and named imports.
trying to get it working this set-up but I don't know what I have done wrong
EDIT:
this is how I am exporting the files
export function Navbar() {
return (
<div>
<h1>this is a navbar</h1>
</div>
);
}
In the index file
export * from "./Header/Header";
export * from "./Navbar/Navbar";
You should export default your component
export default function Navbar() {
return (
<div>
<h1>this is a navbar</h1>
</div>
);
}
and remove default export in exportedObject component
const exportedObject = {
Header,
Navbar,
};
export exportedObject;
I have forms to Post Article in my blog Django2. When I run django server there is no error, but when I Post and submit Article in my frontEnd apps nothing happens and doesn't save any data.
Any help on this would be highly appreciated!
Template HTML
<div class="create-article">
<h2>Create an Awesome New Articles</h2>
<form class="site-form" action="{% url 'articles:create' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create">
</form>
</div>
forms.py
from django import forms
from . import models
class CreateArticle(forms.ModelForm):
class Meta:
model = models.Article
fields = ['title', 'body', 'slug', 'thumb']
views.py
def article_create(request):
if request.method == 'POST':
form = forms.CreateArticle(request.POST, request.FILES)
if form.is_valid():
# save article to db
instance = form.save(commit=False)
instance.author = request.user
instance.save
return redirect('articles:list')
else:
form = forms.CreateArticle()
return render(request, 'articles/article_create.html', {'form': form})
urls.py
from django.urls import path
from . import views
app_name = 'articles'
urlpatterns = [
path('', views.article_list, name="list"),
path('create/', views.article_create, name="create"),
path('<slug>/', views.article_detail, name="detail"),
]
Thanks.
It starts here: instance = form.save(commit=False), where you are not commiting the save.
Further down you have instance.save as if you were setting a model field, but with not value given to it.
Make that line instance.save() instead.
Im trying to use markdown together with Templetor in web.py but I can't figure out what Im missing
Documentation is here http://webpy.org/docs/0.3/templetor#builtins
import markdown
t_globals = {
'datestr': web.datestr,
'markdown': markdown.markdown
}
render = web.template.render(globals=t_globals)
class Blog:
def GET(self, post_slug):
""" Render single post """
post = BlogPost.get(BlogPost.slug == post_slug)
render = web.template.render(base="layout")
return render.post({
"blogpost_title": post.title,
"blogpost_content": post.content,
"blogpost_teaser": post.teaser
})
here is how I try to use markdown inside the post.html template
$def with (values)
$var title: $values['blogpost_title']
<article class="post">
<div class="post-meta">
<h1 class="post-title">$values['blogpost_title']</h1>
</div>
<section class="post-content">
<a name="topofpage"></a>
$:markdown(values['blogpost_content'])
</section>
But Im getting this exception
type 'exceptions.NameError' at
/blog/he-ll-want-to-use-your-yacht-and-i-don-t-want-this-thing-smelling-like-fish/
global name 'markdown' is not defined
You're re-initializing render, once in global scope setting globals and once within Blog.GET setting base. Do it only once!
I have my controller in the folder controllers with the name AdController
and my action name is
/**
* action ajaxValue
*
* #param string $argument
* #return void
*/
public function ajaxValueAction($argument = NULL) {
}
and my template file is on location Resources/Private/Templates/Ad/ajaxValue.html
with the name ajaxValue.html
{namespace t=Helhum\TyposcriptRendering\ViewHelpers}
<f:layout name="Default" />
This Template is responsible for creating a table of domain objects.
If you modify this template, do not forget to change the overwrite settings
in /Configuration/ExtensionBuilder/settings.yaml:
Resources:
Private:
Templates:
List.html: keep
Otherwise your changes will be overwritten the next time you save the extension in the extension builder
<f:section name="main">
<f:debug title="Results of customers query">{ads}</f:debug>
<f:flashMessages />
<!-- Category selection box -->
<!-- This is basically called a ajax request which is based on some other file take from the following link http://ajax.helmut-hummel.de/
-->
<div id="dataJson" data-url="{t:uri.ajaxAction(action: 'ajaxValue', format: 'json', controller: 'Ad', pluginName: 'Txcasmarketing') -> f:format.htmlentities()}"></div>
<div class="container">
<div class="btn-group">
<a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#">Select Category<span class="caret"></span></a>
<ul class="dropdown-menu">
<f:for each="{categories}" as="category">
<li>
<a data-catUid="{category.uid}" href="#">{category.name}</a>
</li>
</f:for>
</ul>
</div>
</div>
I am getting the following error
<p><strong>Sorry, the requested view was not found.</strong></p> <p>The technical reason is: <em>No template was found. View could not be resolved for action "ajaxValue" in class "CASmarketing\Casmarketing\Controller\AdController"</em>.</p>
The defaults templates which has been created by extension builder is accessible. the structure of my ex_localconf.php is
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'CASmarketing.Casmarketing',
'Txcasmarketing', [
'State' => 'list, show, new, create, edit, update, delete',
'Category' => 'list, show, new, create, edit, update, delete',
'Ad' => 'list, ajaxValue, show, new, create, edit, update, delete'
],
// non-cacheable actions
[
'State' => 'create, update, delete',
'Category' => 'create, update, delete',
'Ad' => 'create, update, delete'
]
);
}, $_EXTKEY
);
and my template file is on location Resources/Templates/Ad/ajaxValue.html
with the name ajaxValue.html
and my step.ts file sitting is
plugin.tx_casmarketing_txcasmarketing {
view {
templateRootPaths.0 = EXT:casmarketing/Resources/Private/Templates/
templateRootPaths.1 = {
$plugin.tx_casmarketing_txcasmarketing.view.templateRootPath}
partialRootPaths.0 = EXT:casmarketing/Resources/Private/Partials/
partialRootPaths.1 = {
$plugin.tx_casmarketing_txcasmarketing.view.partialRootPath}
layoutRootPaths.0 = EXT:casmarketing/Resources/Private/Layouts/
layoutRootPaths.1 = {
$plugin.tx_casmarketing_txcasmarketing.view.layoutRootPath}
}
persistence {
storagePid = {
$plugin.tx_casmarketing_txcasmarketing.persistence.storagePid}
#recursive = 1
}
features {
#skipDefaultArguments = 1
}
mvc {
#callDefaultActionIfActionCantBeResolved = 1
}
}
my script file which is basically called the ajax request which is define in the pageLayout.js
$(".dropdown-menu li a").click(function () {
var jsonUrl = $('#dataJson').attr('data-url')
var selectedCatUid = $(this).attr('data-catUid');
$.ajax({
type: 'POST',
url: jsonUrl,
data: {
'tx_casmarketing_txcasmarketing[catId]': selectedCatUid
},
success: function (response) {
alert(response);
},
});
Your template should not be in Resources/Templates/Ad/ajaxValue.html but in Resources/Private/Templates/Ad/AjaxValue.html. Mind the Private sub folder. Also it has to be UpperCase.
Didn't know that it does matter but the filename usually is uppercase. You also should make sure that the typoscript settings are configured to this directory.
Your typoscript should correctly look like this:
plugin.tx_casmarketing_txcasmarketing {
view {
templateRootPaths.0 = EXT:casmarketing/Resources/Private/Templates/
templateRootPaths.1 = {$plugin.tx_casmarketing_txcasmarketing.view.templateRootPath}
partialRootPaths.0 = EXT:casmarketing/Resources/Private/Partials/
partialRootPaths.1 = {$plugin.tx_casmarketing_txcasmarketing.view.partialRootPath}
layoutRootPaths.0 = EXT:casmarketing/Resources/Private/Layouts/
layoutRootPaths.1 = {$plugin.tx_casmarketing_txcasmarketing.view.layoutRootPath}
}
persistence {
storagePid = {$plugin.tx_casmarketing_txcasmarketing.persistence.storagePid}
#recursive = 1
}
features {
#skipDefaultArguments = 1
}
mvc {
#callDefaultActionIfActionCantBeResolved = 1
}
}
If you change this in your setup.txt of the extension this is hardly cached and you have to clear the cache in the install tool. After making sure your typoscript is correctly loaded place your new Views template inside the ext-directory template path first to try it out.
If this does not help please give us the content of your HTML Template.
I have an application that in the admin area there is options such as
Background image: [ File Upload ]
Top Illustration: [ File Upload ]
and in the front end I want to easily attach this info to the CSS, maybe teh simply way should be
.background {
background: url(<%: Model.BackgroundUrl %>);
...
}
I currently have my Css files unde ~/Content/Css
shall I have a View with this and change the content type so I can use the Model part?
What other techniques are available or this situation?
Thank you.
You cannot use the model in a static CSS file. If you want to achieve this you will need to generate it dynamically using a controller action. As an alternative you could directly use an img tag:
<img src="<%: Model.BackgroundUrl %>" alt="" />
I ended up doing a new View and set all up as:
in the Master Template
<link href="<%= Url.Content(
String.Format("~/{0}/Css/CustomCss.aspx",
ViewData["CalendarUrl"])) %>"
rel="stylesheet" type="text/css" />
in the Routes
routes.MapRoute(
"CustomCss", // Route name
"{calurl}/Css/CustomCss.aspx", // URL with parameters
new { calurl = "none", controller = "Content", action = "CustomCss", id = UrlParameter.Optional } // Parameter defaults
);
in the Controller: Content, Action: CustomCss
// GET: /Css/CustomCss
public ActionResult CustomCss(string calurl)
{
return View();
}
in my View (placed in Shared):
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>"
ContentType="text/css" %>
<%
string company_logo = ViewData["CompanyLogo"] as string;
string company_bkg = ViewData["CompanyBackground"] as string;
%>
.background {
<%if (!String.IsNullOrWhiteSpace(company_bkg))
{ %>background-image:url('<%: company_bkg %>');<%} %>
}
#header-content{
<%if (!String.IsNullOrWhiteSpace(company_logo ))
{ %>background-image:url('<%: company_logo %>');<%} %>
}