Tailwind CSS autocomplete inside Twig variables - visual-studio-code

I am using TailwindCSS with TWIG files. The purgecss works fine inside CSS files and also inside "normal" markup like
<div class="font-bold text-blue"></div>
But we are developing mostly Drupal TWIG templates and a lot of our TWIG files setting classes to an attributes array. And the bellow doesn't work.
attributes.addClass(['font-bold', 'bg-blue']);
or
{% set classes = ['font-bold', color == 'blue' ? 'bg-blue'] %}
This is my purgecss configuration:
gulp.task(
"styles",
gulp.series("sass", function () {
const postcssimport = require("postcss-import");
return gulp
.src("src/styles.css")
.pipe(sass().on("error", sass.logError))
.pipe(
postcss([
postcssimport(),
tailwindcss("./tailwind.config.js"),
autoprefixer,
])
)
.pipe(
purgecss({
mode: "layers",
content: ["templates/**/*.twig", "src/scss/**/*.scss"],
defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
})
)
.pipe(gulp.dest("./css"));
})
);
Do you have any idea about this?
Thank you.

The TailwindCSS Intellisense plugin for VS code has an experimental setting that lets you set custom regex expressions that fire autocomplete. It's announced by the plugin's author here:
https://github.com/tailwindlabs/tailwindcss-intellisense/issues/129#issuecomment-735915659
I use these 2 regular expressions to activate autocomplete for {% set classes = [] } and <element{{ attributes.addClass() }}> respectively:
"tailwindCSS.experimental.classRegex": [
["classes =.+\\[([^\\]]*)\\]","'([^']*)'"],
["addClass\\(([^\\)]*)\\)","'([^']*)'"]
]
This goes into the main settings.json file for VS Code.

Related

Wrong TSX ternary markup block formatting in VSCode

I like 'format on save' VSCode feature very much. But now I'm experiencing annoying wrong formatting of tsx files in VS Code (1.49.2).
Here is an example. Here two lines have extra indents ('single' block)
import React from 'react';
const TestComponent = (props: { isList: boolean }) => {
return (
<div>
{props.isList ? (
<div>liiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiist</div>
) : (
<div>siiiiiiiiiiiiiiiiiiiiiiiingle</div>
)}
</div>
);
};
export default TestComponent;
the same code in jsx file is formatted correctly
import React from 'react';
const TestComponent = props => {
return (
<div>
{props.isList ? (
<div>liiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiist</div>
) : (
<div>siiiiiiiiiiiiiiiiiiiiiiiingle</div>
)}
</div>
);
};
export default TestComponent;
I tried to switch default vscode formatter to eslint, null, prettier (user/workspace) - no difference. When I run prettier --write src/components/TestComponent.tsx the tsx file is formatted correctly.
I also checked typescript-specific formatting settings in VS Code, but couldn't find anything related. For the test I've removed .eslint.js config file and my project doesn't have .prettierrc config.
it was wrong formatter specified in $HOME/.config/Code/User/settings.json (on Linux), something like
"[typescriptreact]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
}
it should be either set to esbenp.prettier-vscode or removed in order to use the default one
I fixed this problem by going to my user settings and deleting
"[javascript]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
},
and configuring prettier to be the default formatter

How to set a formatter in vscode for HTML and Jinja?

I'm using vs code and it has auto formating which is great, however, when I write HTML files and use Jinja or DTL, it formats terribly. How do I either disable formatting for this or change it?
I've installed an extension for formatting called Prettier.
This is what I get:
{{ block.super }}
{% endblock styling%} {% block title %} Game {{ game.firs_player }} vs.
{{ game.second_player }} {% endblock title %} {% block content %} This is a
detial page for game {{ game.id }}
{% endblock content %}
This is what I want:
{% load staticfiles %}
{% block styling%}
{{ block.super }}
{% endblock styling%}
{% block title %}
Game {{ game.firs_player }} vs.{{ game.second_player }}
{% endblock title %}
{% block content %}
This is a detial page for game {{ game.id }}
{% endblock content %}```
You could use beautify. It isn't perfect, but it gets the job done.
After you installed it, add this to your settings.json file:
"beautify.language": {
"js": {
"type": [
"javascript"
],
"filename": [
".jshintrc",
".jsbeautifyrc"
]
// "ext": ["js", "json"]
// ^^ to set extensions to be beautified using the javascript beautifier
},
"css": [
"css",
"scss"
],
"html": [
"htm",
"html",
"django-html"
]
// ^^ providing just an array sets the VS Code file type
},
Now, it should work with Django template files.
For some reason I wasn't able to get Daniel's, beautify solution to work. Maybe because I'm using Prettier globally.
Here's what worked for me:
There's a project called Unibeautify that seems kind of like a "one ring to rule them all" for tying together personalized settings across different formatters and filetypes.
It has a VS Code extension, VSCode-Unibeautify.
After installing the extension, you need to create a config file and tell VS Code where to find it. You can create and customize your own config if you want to use it for multiple languages, but here's what worked for me for Jinja:
# unibeautifyrc.yaml
HTML:
beautifiers:
- JS-Beautify
- Pretty Diff
and then, in your vscode settings:
// settings.json
"unibeautify.defaultConfig": "/PATH/TO/unibeautifyrc.yaml",
"unibeautify.enabled": true,
"[jinja-html]": {
"editor.defaultFormatter": "Glavin001.unibeautify-vscode",
"editor.formatOnSave": true
},
What I've done also, is to associate html files with the Jinja filetype in my project's settings.json. This lets you use prettifier for other files, and also other projects where you're not using Jinja. I think you could also make the below *.html more specific to your templates directory if you prefer.
// MYPROJECT/.vscode/settings.json
{
"files.associations": {
"*.html": "jinja-html"
}
}
This solution is powered by JS-Beautify which seems to work well with Jinja and powers Atoms atom-beautify extension, also by the same author of Unibeautify, Glavin001, a beautiful individual.

Jsx indentation conflict vscode and eslint

Eslint(airbnb config) wants to have my params on new lines when I have multiple params. But when I do that, vscode formatting keeps giving 4 spaces indentation instead of 2 as expected.
Result:
const Example = ({
param1,
param2,
param3,
}) => (
<div>
{param1} {param2} {param3}
</div>
);
expected:
const Example = ({
param1,
param2,
param3,
}) => (
<div>
{param1} {param2} {param3}
</div>
);
Is there a setting I can use in vscode to get the expected behavior?
You can avoid conflicting rules by using eslint-config-prettier or preferably prettier-eslint integration. This integration will use eslint config for formatting the rules and there won't be any conflicts.
If you are using VS Code, there is a config option for prettier-vscode

Silverstripe: How to allow javascript in tinymce?

Admins and editors on one of my sites wants to include some javascript embeds like twitter, facebook, instagram or whatever, on pages. I thought it would be really easy to just set the extended_valid_elements to allow the script tag in the html editor of tinyMCE, but it apparently doesn't work.
I've added this to my config
HtmlEditorConfig::get('cms')->setOption(
'extended_valid_elements',
'script[charset|defer|language|src|type|async]'
);
And I've checked that it's passed to the ssTinyMCEconfig variable in my dom.
So far so good. But when I try to post a simple script in to my HTML-editor, it strips it. Does anyone know how this can be fixed?
Thank you!
Rather than manage custom scripts through the TinyMCE editor we could add a text variable to $db to manage the custom scripts through a plain TextareaField.
The following code works for SilverStripe 3.4:
class Page extends SiteTree {
private static $db = array(
'CustomScript' => 'Text'
);
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root.CustomScript',
TextareaField::create('CustomScript', 'Custom Script')
->setRows(30)
->addExtraClass('code')
->setAttribute('spellcheck', 'false'));
return $fields;
}
}
Here is some custom css for the CMS to make the script input fields display the text with a monospace font.
mysite/css/cms.css
.field.code textarea {
max-width: 100%;
font-family: "Courier New", Courier, monospace;
color: #000000;
background: #ffffff;
}
We enable the custom css in the cms with the following code in our config.yml file:
mysite/_config/config.yml
LeftAndMain:
extra_requirements_css:
- 'mysite/css/cms.css'
In our Page.ss template in the head tag, or at the bottom of the body tag, or whether we would like the custom script, we put the following to load our custom script:
<% if $CustomScript %>
$CustomScript.RAW
<% end_if %>
If we want site wide custom scripts we could also add this field to the Settings tab by extending our SiteConfig:
mysite/code/extensions/CustomSiteConfig.php
class CustomSiteConfig extends DataExtension {
private static $db = array(
'CustomScript' => 'Text'
);
public function updateCMSFields(FieldList $fields) {
$fields->addFieldToTab('Root.CustomScript',
TextareaField::create('CustomScript', 'Custom Script')
->setRows(30)
->addExtraClass('code')
->setAttribute('spellcheck', 'false'));
}
}
We enable this SiteConfig extension in our config.yml file:
mysite/_config/config.yml
SiteConfig:
extensions:
- CustomSiteConfig
In our Page.ss template in the head tag, or at the bottom of the body tag, we put the following to load our site wide custom script:
<% if $SiteConfig.CustomScript %>
$SiteConfig.CustomScript.RAW
<% end_if %>
I was able to get around the issue for Twitter embed by simply including the relevant script links in my header. This embedded the twitter-tweet blockquote code that I pasted into TimyMCE.

Symfony2 TinymceBundle

I created an ArticleController to render a form with fields: title (text) and content (textarea), and everything works well until I add class="tinymce" to the textarea field in the template. then I get this error:
'An invalid form control with name='form[content]' is not focusable.'
I followed the documentation to add the 'class' attribute and the editor renders fine in the browser, its just when I submit the form I get the error.
Any ideas what could be causing this?
{{ form_errors(form) }}
{{ form_widget(form.title) }}
{{ form_widget(form.content, { 'attr': {'class': 'tinymce' }} ) }}
{{ form_rest(form) }}
<input type="submit" />
Apparently there is an issue with chrome regarding the attribute 'required = "true"'.
http://code.google.com/p/chromium/issues/detail?id=45640
I added 'formnovalidate = "true"' attribute to the submit button input field and it works fine
tinyMCE.init({
mode : "specific_textareas",
editor_selector : "mceEditor",
setup : function(ed) {
ed.onChange.add(function(ed, l) {
tinyMCE.activeEditor.getElement().value = tinyMCE.activeEditor.getContent();
});
}
});
I tried the suggestion from Musefan, and it only partly worked, but it got me experimenting.
Here's something that works for me. Tested on Firefox 10.0.1, IE9, and Chrome 17.
Where I'm setting tinyMCE.activeEditor.getElement().value = 'test' it can be any value other than ''. Not sure why that's true.
tinyMCE.init({
mode : "specific_textareas",
editor_selector : "tinymce",
setup : function(ed)
{
// This is needed when the textarea is required for html5
ed.onInit.add(function(ed)
{
tinyMCE.activeEditor.getElement().value = 'test'
});
},
});
The error happens when the WYSIWYG hides your textarea but the textarea is set to required field. You can set 'required' => false on your content textarea control when you build the form in order to disable browser's required check.
$builder->add("content", "textarea", array('required' => false));
tinyMCE will normally update the contents of the hidden textarea during the onsubmit-Event.
This event, however, is not fired when html5-validation is used and any input is invalid.
Therefore you will never get an empty and required textarea with tinyMCE on top to validate correctly unless you enforce the textarea to be updated before html5-validation starts.
I built a workaround for this bug which hopefully will be merged into the original repo anytime soon: https://github.com/stfalcon/TinymceBundle/pull/19
Building on musefans's response above.
I came here because I'm using Simple Form, Twitter Bootstrap, and tinymce-rails. If you're using tinymce-rails this setup you need to edit the line noted in is answer to your tinymce.yml file. Your final file should look similar to this.
theme_advanced_toolbar_location: top
theme_advanced_toolbar_align: left
theme_advanced_statusbar_location: bottom
theme_advanced_buttons3_add:
- tablecontrols
- fullscreen
plugins:
- table
- fullscreen
mode:
- specific_textareas