feat(npm): updated npm installer

Updated release so npm package will be deployed.

closes #192
This commit is contained in:
Christopher Pickering 2022-07-06 11:24:45 -05:00
parent f688a0b050
commit 4c0caccdf6
No known key found for this signature in database
GPG key ID: E14DB3B0A0FACF84
40 changed files with 10714 additions and 1400 deletions

View file

@ -13,3 +13,9 @@ indent_size = 2
[*.js] [*.js]
indent_size = 2 indent_size = 2
[*.yml]
indent_size = 2
[*.yaml]
indent_size = 2

View file

@ -35,3 +35,37 @@ jobs:
files: ./coverage.xml files: ./coverage.xml
fail_ci_if_error: true fail_ci_if_error: true
verbose: true verbose: true
test_npm:
name: python ${{ matrix.python-version }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python-version: [3.7, 3.8, 3.9, '3.10']
node: [ 12, 14, 16 ]
fail-fast: true
steps:
- name: checkout
uses: actions/checkout@v3
- name: setup python ${{ matrix.python-version }} on ${{ matrix.os }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: setup node ${{ matrix.node }} on ${{ matrix.os }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node }}
- name: install project
run: npm --omit=dev install
- name: test post install
run: node ./bin/install.js
- name: test run help
run: node ./bin/index.js -h
- name: test run lint
run: echo "<div>" | node ./bin/index.js
- name: test run check
run: echo "<div>" | node ./bin/index.js --check

7
.prettierignore Normal file
View file

@ -0,0 +1,7 @@
node_modules/*
docs/_site/*
dist/*
.mypy_cache/*
.pytest_cache/*
.tox/*
tests/*

11
.prettierrc Normal file
View file

@ -0,0 +1,11 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": true,
"arrowParens": "always",
"jsxBracketSameLine": false,
"semi": true
}

View file

@ -58,6 +58,12 @@ Grab it with `pip`
pip install djlint pip install djlint
``` ```
*Or with the npm experimental install - Note, this requires python and pip to be on your system path.*
```bash
npm i djlint
```
Lint your project Lint your project
```bash ```bash

View file

@ -1,110 +1,186 @@
const process = require('process');
const { PythonShell } = require('python-shell');
const {spawn} = require('child_process'); PythonShell.defaultOptions = {
const yargs = require("yargs"); mode: 'text',
const stdin = process.stdin; pythonOptions: ['-u'],
env: { PYCHARM_HOSTED: 1 }, // Force color
function getStdin () {
// https://github.com/sindresorhus/get-stdin/pull/19/files
let ret = '';
return new Promise(resolve => {
if (stdin.isTTY) {
resolve(ret);
return;
}
const timeout = setTimeout(() => {
resolve(ret);
}, 100);
stdin.unref();
stdin.setEncoding('utf8');
stdin.on('readable', () => {
clearTimeout(timeout);
stdin.ref();
let chunk;
while ((chunk = stdin.read())) {
ret += chunk;
}
});
stdin.on('end', () => {
resolve(ret);
});
});
}; };
function clean(output) {
getStdin().then(str => {run(str)}) return output.replaceAll('python -m ', '');
function clean(output){
return output
.replaceAll("undefined", "")
.replaceAll("python -m djlint", "djlint")
} }
function run(stdin){ const yargs = require('yargs');
var dataToSend; const stdin = process.stdin;
const exitCode=0;
const options= yargs
.scriptName('djlint')
.usage(`Usage: $0 [OPTIONS] SRC ...
djLint · lint and reformat HTML templates.`) function getStdin() {
.option("e", { alias: "extension", describe: "File extension to check [default: html]", type: "string", demandOption: false }) // https://github.com/sindresorhus/get-stdin/pull/19/files
.option("i", { alias: "ignore", describe: "Codes to ignore. ex: \"H014,H017\"", type: "string", demandOption: false }) let returnValue = '';
.option("reformat", { describe: "Reformat the file(s).", type: "boolean", demandOption: false })
.option("check", { describe: "Check formatting on the file(s).", type: "boolean", demandOption: false })
.option("indent", { describe: "Indent spacing. [default: 4]", type: "int", demandOption: false })
.option("quiet", { describe: "Do not print diff when reformatting.", type: "boolean", demandOption: false })
.option("profile", { describe: "Enable defaults by template language. ops: django, jinja, nunjucks, handlebars, golang, angular, html [default: html]", type: "string", demandOption: false })
.option("require-pragma", { describe: "Only format or lint files that starts with a comment with the text 'djlint:on'", type: "boolean", demandOption: false })
.option("lint", { describe: "Lint for common issues. [default option]", type: "boolean", demandOption: false })
.option("use-gitignore", { describe: "Use .gitignore file to extend excludes.", type: "boolean", demandOption: false })
.argv;
// set flags return new Promise((resolve) => {
const quiet = options.quiet ? '--quiet' : undefined if (stdin.isTTY) {
const reformat = options.reformat ? '--reformat' : undefined resolve(returnValue);
const check = options.check ? '--check' : undefined return;
const require_pragma = options["require-pragma"] ? '--require-pragma' : undefined
const lint = options.lint ? '--lint' : undefined
const use_gitignore = options["use-gitignore"] ? '--use-gitignore' : undefined
const has_stdin = stdin !== "" ? "-": options._[0]
// set variables
const indent = options.indent ? '--indent='+options.indent : undefined
const profile =options.profile ? '--profile='+options.profile : undefined
const ignore = options.ignore ? '--ignore='+options.ignore : undefined
const args = [has_stdin, quiet,reformat,check,require_pragma,lint,use_gitignore, indent, profile, ignore].filter(x => {return x !== undefined})
const python = spawn('python3', ['-m', 'djlint', ...args], {"cwd": "./src"});
if(stdin !== ""){
python.stdin.write(stdin);
python.stdin.end()
} }
python.stdout.on('data', function (data) { const timeout = setTimeout(() => {
dataToSend += data//.toString(); resolve(returnValue);
}, 100);
stdin.unref();
stdin.setEncoding('utf8');
stdin.on('readable', () => {
clearTimeout(timeout);
stdin.ref();
let chunk;
while ((chunk = stdin.read())) {
returnValue += chunk;
}
}); });
python.stderr.on('data', function (data) { stdin.on('end', () => {
dataToSend += data//.toString(); resolve(returnValue);
}); });
});
python.on('close', (code) => { }
process.stdout.write(clean(dataToSend))
process.exit(code) getStdin().then((string_) => {
}); run(string_);
});
function run(stdin) {
const options = yargs
.scriptName('djlint')
.usage(
`Usage: $0 [OPTIONS] SRC ...
djLint · lint and reformat HTML templates.`,
)
.option('e', {
alias: 'extension',
describe: 'File extension to check [default: html]',
type: 'string',
demandOption: false,
})
.option('h', {
alias: 'help',
describe: 'Show this message and exit.',
type: 'boolean',
demandOption: false,
})
.option('i', {
alias: 'ignore',
describe: 'Codes to ignore. ex: "H014,H017"',
type: 'string',
demandOption: false,
})
.option('reformat', {
describe: 'Reformat the file(s).',
type: 'boolean',
demandOption: false,
})
.option('check', {
describe: 'Check formatting on the file(s).',
type: 'boolean',
demandOption: false,
})
.option('indent', {
describe: 'Indent spacing. [default: 4]',
type: 'int',
demandOption: false,
})
.option('quiet', {
describe: 'Do not print diff when reformatting.',
type: 'boolean',
demandOption: false,
})
.option('warn', {
describe: 'Return errors as warnings.',
type: 'boolean',
demandOption: false,
})
.option('profile', {
describe:
'Enable defaults by template language. ops: django, jinja, nunjucks, handlebars, golang, angular, html [default: html]',
type: 'string',
demandOption: false,
})
.option('require-pragma', {
describe:
"Only format or lint files that starts with a comment with the text 'djlint:on'",
type: 'boolean',
demandOption: false,
})
.option('lint', {
describe: 'Lint for common issues. [default option]',
type: 'boolean',
demandOption: false,
})
.option('use-gitignore', {
describe: 'Use .gitignore file to extend excludes.',
type: 'boolean',
demandOption: false,
}).argv;
// Set flags
const quiet = options.quiet ? '--quiet' : undefined;
const help = options.h ? '--help' : undefined;
const warn = options.warn ? '--warn' : undefined;
const reformat = options.reformat ? '--reformat' : undefined;
const check = options.check ? '--check' : undefined;
const require_pragma = options['require-pragma']
? '--require-pragma'
: undefined;
const lint = options.lint ? '--lint' : undefined;
const use_gitignore = options['use-gitignore']
? '--use-gitignore'
: undefined;
const has_stdin = stdin === '' ? options._[0] : '-';
// Set variables
const indent = options.indent ? '--indent=' + options.indent : undefined;
const profile = options.profile ? '--profile=' + options.profile : undefined;
const ignore = options.ignore ? '--ignore=' + options.ignore : undefined;
const extension = options.e ? '-e=' + options.extension : undefined;
const args = [
has_stdin,
warn,
help,
quiet,
extension,
reformat,
check,
require_pragma,
lint,
use_gitignore,
indent,
profile,
ignore,
].filter((x) => {
return x !== undefined;
});
const pyshell = new PythonShell('-m', { args: ['djlint', ...args] });
if (stdin !== '') {
pyshell.send(stdin);
}
pyshell.on('message', function (message) {
console.log(clean(message));
});
pyshell.on('stderr', function (message) {
console.log(clean(message));
});
pyshell.end(function (error, code) {
process.exit(code);
});
} }

View file

@ -1,17 +1,21 @@
const {spawn} = require('child_process'); const { PythonShell } = require('python-shell');
var dataToSend;
const python = spawn('python3', ['-m', 'pip', 'install', '--upgrade','--quiet', '-r', '../requirements.txt'], {"cwd": "./src"});
PythonShell.defaultOptions = {};
const options = {
mode: 'text',
args: ['pip', 'install', 'djlint'],
pythonOptions: ['-u'],
env: { PYCHARM_HOSTED: 1 },
};
python.stdout.on('data', function (data) { try {
dataToSend += data.toString(); PythonShell.getVersionSync();
});
python.stderr.on('data', function (data) { PythonShell.run('-m', options, function (error, results) {
dataToSend += data.toString(); if (error) throw error;
}); console.log(results.join('\n'));
});
python.on('close', (code) => { } catch (e) {
process.stdout.write(dataToSend.replace("undefined","")) console.log(e.message);
process.exit(code) process.exit(1);
}); }

View file

@ -1,31 +1,38 @@
const Image = require("@11ty/eleventy-img"); const Image = require('@11ty/eleventy-img');
const syntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight"); const syntaxHighlight = require('@11ty/eleventy-plugin-syntaxhighlight');
const criticalCss = require("eleventy-critical-css"); const criticalCss = require('eleventy-critical-css');
const slugify = require("slugify"); const slugify = require('slugify');
const metagen = require("eleventy-plugin-metagen"); const metagen = require('eleventy-plugin-metagen');
const i18n = require('eleventy-plugin-i18n'); const i18n = require('eleventy-plugin-i18n');
const translations = require('./src/_data/i18n'); const translations = require('./src/_data/i18n');
const locales = require('./src/_data/locales'); const locales = require('./src/_data/locales');
const fs = require('fs'); const fs = require('fs');
const outdent = require('outdent'); const outdent = require('outdent');
const schema = require("@quasibit/eleventy-plugin-schema"); const schema = require('@quasibit/eleventy-plugin-schema');
const editOnGithub = require('eleventy-plugin-edit-on-github'); const editOnGithub = require('eleventy-plugin-edit-on-github');
const i18n_func = require('eleventy-plugin-i18n/i18n.js'); const i18n_func = require('eleventy-plugin-i18n/i18n.js');
const slugifyCustom = (s) => const slugifyCustom = (s) =>
slugify(s, { lower: true, remove: /[*+~.()'"!:@]/g }); slugify(s, { lower: true, remove: /[*+~.()'"!:@]/g });
async function imageShortcode(src, alt, sizes, type='asdf', loading="lazy", decoding="async") { async function imageShortcode(
src,
alt,
sizes,
type = 'asdf',
loading = 'lazy',
decoding = 'async',
) {
let metadata = await Image(src, { let metadata = await Image(src, {
widths: [24, 300, 400, 500, 600, 800, 1200], widths: [24, 300, 400, 500, 600, 800, 1200],
formats: ["webp", "png"], formats: ['webp', 'png'],
sharpWebpOptions: { sharpWebpOptions: {
options: { options: {
quality:70 quality: 70,
} },
}, },
outputDir: "./_site/static/img/", outputDir: './_site/static/img/',
urlPath: "/static/img/" urlPath: '/static/img/',
}); });
let imageAttributes = { let imageAttributes = {
@ -35,16 +42,26 @@ async function imageShortcode(src, alt, sizes, type='asdf', loading="lazy", deco
decoding: decoding, decoding: decoding,
}; };
if(type=="boxed"){ if (type == 'boxed') {
return `<div class="block"><div class="box is-inlineblock">` + Image.generateHTML(metadata, imageAttributes) + `</div></div>`; return (
`<div class="block"><div class="box is-inlineblock">` +
Image.generateHTML(metadata, imageAttributes) +
`</div></div>`
);
} }
// using custom code so that we can return the highest src in img as old browsers don't auto upscale. // using custom code so that we can return the highest src in img as old browsers don't auto upscale.
let lowsrc = metadata.png[0]; let lowsrc = metadata.png[0];
let highsrc = metadata.png[metadata.png.length - 1]; let highsrc = metadata.png[metadata.png.length - 1];
return `<picture> return `<picture>
${Object.values(metadata).map(imageFormat => { ${Object.values(metadata)
return ` <source type="${imageFormat[0].sourceType}" srcset="${imageFormat.map(entry => entry.srcset).join(", ")}" sizes="${sizes}">`; .map((imageFormat) => {
}).join("\n")} return ` <source type="${
imageFormat[0].sourceType
}" srcset="${imageFormat
.map((entry) => entry.srcset)
.join(', ')}" sizes="${sizes}">`;
})
.join('\n')}
<img <img
src="${highsrc.url}" src="${highsrc.url}"
width="${highsrc.width}" width="${highsrc.width}"
@ -58,18 +75,20 @@ async function imageShortcode(src, alt, sizes, type='asdf', loading="lazy", deco
// from https://github.com/pusher/docs/blob/main/.eleventy.js // from https://github.com/pusher/docs/blob/main/.eleventy.js
// widont is a function that takes a string and replaces the space between the last two words with a non breaking space. This stops typographic widows forming // widont is a function that takes a string and replaces the space between the last two words with a non breaking space. This stops typographic widows forming
const widont = (string) => { const widont = (string) => {
return string.split(" ").length > 2 return string.split(' ').length > 2
? string.replace(/\s([^\s<]+)\s*$/, "\u00A0$1") ? string.replace(/\s([^\s<]+)\s*$/, '\u00A0$1')
: string; : string;
}; };
module.exports = function(eleventyConfig) { module.exports = function (eleventyConfig) {
eleventyConfig.setUseGitIgnore(false); eleventyConfig.setUseGitIgnore(false);
eleventyConfig.addFilter("widont", widont); eleventyConfig.addFilter('widont', widont);
eleventyConfig.addWatchTarget("./src/static/"); eleventyConfig.addWatchTarget('./src/static/');
eleventyConfig.addNunjucksAsyncShortcode("image", imageShortcode); eleventyConfig.addNunjucksAsyncShortcode('image', imageShortcode);
eleventyConfig.addTransform("htmlmin", require("./src/_utils/minify-html.js")); eleventyConfig.addTransform(
'htmlmin',
require('./src/_utils/minify-html.js'),
);
eleventyConfig.addPlugin(syntaxHighlight); eleventyConfig.addPlugin(syntaxHighlight);
eleventyConfig.addPlugin(metagen); eleventyConfig.addPlugin(metagen);
eleventyConfig.addPlugin(criticalCss); eleventyConfig.addPlugin(criticalCss);
@ -78,18 +97,27 @@ module.exports = function(eleventyConfig) {
// required // required
github_edit_repo: 'https://github.com/Riverside-Healthcare/djLint', github_edit_repo: 'https://github.com/Riverside-Healthcare/djLint',
// optional: defaults // optional: defaults
github_edit_path: "/docs/", // non-root location in git url. root is assumed github_edit_path: '/docs/', // non-root location in git url. root is assumed
github_edit_branch: 'master', github_edit_branch: 'master',
github_edit_text: (page) => { github_edit_text: (page) => {
i18n_options = Object.assign(
{},
{
translations,
fallbackLocales: {
'*': 'en-US',
},
},
);
i18n_options = Object.assign({},{ return `<span class="icon-text"><span class="icon mr-1"><i class="fas fa-pencil"></i></span><span>${i18n_func(
translations, 'edit_page',
fallbackLocales: { undefined,
'*': 'en-US' undefined,
}}) i18n_options,
page,
return `<span class="icon-text"><span class="icon mr-1"><i class="fas fa-pencil"></i></span><span>${i18n_func("edit_page", undefined,undefined, i18n_options, page)}</span></span>`; )}</span></span>`;
return x.inputPath return x.inputPath;
}, },
github_edit_class: 'edit-on-github', github_edit_class: 'edit-on-github',
github_edit_tag: 'a', github_edit_tag: 'a',
@ -98,8 +126,8 @@ module.exports = function(eleventyConfig) {
}); });
/* Markdown Plugins */ /* Markdown Plugins */
const markdownItAnchor = require("markdown-it-anchor"); const markdownItAnchor = require('markdown-it-anchor');
const markdownIt = require("markdown-it")({ const markdownIt = require('markdown-it')({
html: true, html: true,
breaks: true, breaks: true,
linkify: true, linkify: true,
@ -109,9 +137,9 @@ module.exports = function(eleventyConfig) {
const opts = { const opts = {
level: [2, 3, 4, 5], level: [2, 3, 4, 5],
permalink: markdownItAnchor.permalink.linkInsideHeader({ permalink: markdownItAnchor.permalink.linkInsideHeader({
class: "link bn", class: 'link bn',
symbol:"∞", symbol: '∞',
placement: "before" placement: 'before',
}), }),
slugify: slugifyCustom, slugify: slugifyCustom,
}; };
@ -124,76 +152,73 @@ module.exports = function(eleventyConfig) {
h5: 'title is-5', h5: 'title is-5',
h6: 'title is-5', h6: 'title is-5',
p: 'block', p: 'block',
table: 'table' table: 'table',
}; };
markdownIt markdownIt
.use(markdownItAnchor, opts) .use(markdownItAnchor, opts)
.use(require("markdown-it-imsize"), { autofill: true }) .use(require('markdown-it-imsize'), { autofill: true })
.use(require('@toycode/markdown-it-class'), mapping) .use(require('@toycode/markdown-it-class'), mapping)
.use(require('markdown-it-div'), 'div', {}); .use(require('markdown-it-div'), 'div', {});
eleventyConfig.setLibrary("md", markdownIt); eleventyConfig.setLibrary('md', markdownIt);
// copy font // copy font
eleventyConfig.addPassthroughCopy({ eleventyConfig.addPassthroughCopy({
"./node_modules/@fontsource/inter/files": "static/font/inter/files" './node_modules/@fontsource/inter/files': 'static/font/inter/files',
}); });
eleventyConfig.addPassthroughCopy({ eleventyConfig.addPassthroughCopy({
"./node_modules/@fontsource/rasa/files": "static/font/rasa/files" './node_modules/@fontsource/rasa/files': 'static/font/rasa/files',
}); });
eleventyConfig.addPassthroughCopy({ eleventyConfig.addPassthroughCopy({
"./node_modules/@fontsource/crimson-pro/files": "static/font/crimson-pro/files" './node_modules/@fontsource/crimson-pro/files':
'static/font/crimson-pro/files',
}); });
// copy images // copy images
eleventyConfig.addPassthroughCopy({ eleventyConfig.addPassthroughCopy({
"src/static/img": "static/img" 'src/static/img': 'static/img',
}); });
// copy robots // copy robots
eleventyConfig.addPassthroughCopy({ eleventyConfig.addPassthroughCopy({
"src/robots.txt": "robots.txt" 'src/robots.txt': 'robots.txt',
}); });
// copy favicon // copy favicon
eleventyConfig.addPassthroughCopy({ eleventyConfig.addPassthroughCopy({
"src/static/img/favicon.ico": "favicon.ico" 'src/static/img/favicon.ico': 'favicon.ico',
}); });
eleventyConfig.addFilter("jsonify", (text) => { eleventyConfig.addFilter('jsonify', (text) => {
return JSON.stringify(text).replace(/(?:\\n\s*){2,}/g, "\\n"); return JSON.stringify(text).replace(/(?:\\n\s*){2,}/g, '\\n');
}); });
eleventyConfig.addFilter('niceDate', (value) => {
try {
eleventyConfig.addFilter("niceDate", (value) => { const options = { year: 'numeric', month: 'short', day: 'numeric' };
try{ return value.toLocaleDateString('en-us', options);
const options = {year: 'numeric', month: 'short', day: 'numeric' }; } catch (e) {
return value.toLocaleDateString('en-us', options); return value;
} catch (e) { }
return value
}
}); });
eleventyConfig.addFilter("algExcerpt", (text) => { eleventyConfig.addFilter('algExcerpt', (text) => {
return text return text
.replace(/<code class="language-.*?">.*?<\/code>/gs, "") .replace(/<code class="language-.*?">.*?<\/code>/gs, '')
.replace(/<.*?>/g, "") .replace(/<.*?>/g, '')
.substring(0, 8000); .substring(0, 8000);
}); });
eleventyConfig.addCollection("algolia", function(collection) { eleventyConfig.addCollection('algolia', function (collection) {
return collection.getFilteredByGlob("**/*.md"); return collection.getFilteredByGlob('**/*.md');
}); });
const icons = { const icons = {
note: '<span class="icon has-text-info mr-1"><i class="fas fa-pencil"></i></span>', note: '<span class="icon has-text-info mr-1"><i class="fas fa-pencil"></i></span>',
}; };
eleventyConfig.addShortcode("admonition", function(icon, title, text) { eleventyConfig.addShortcode('admonition', function (icon, title, text) {
return outdent` return outdent`
<article class="message ${icon} box"> <article class="message ${icon} box">
<div class="message-header"> <div class="message-header">
@ -203,82 +228,110 @@ module.exports = function(eleventyConfig) {
</article>`; </article>`;
}); });
eleventyConfig.addFilter('markdown', (value) => {
eleventyConfig.addFilter('markdown', value => {
return `${markdownIt.render(value)}`; return `${markdownIt.render(value)}`;
}); });
const { fontawesomeSubset } = require('fontawesome-subset'); const { fontawesomeSubset } = require('fontawesome-subset');
fontawesomeSubset({ fontawesomeSubset(
brands:['discord', 'github'], {
regular:['envelope'], brands: ['discord', 'github'],
solid: ['globe', 'circle-arrow-right', 'pencil', 'infinity','download','code-commit'] regular: ['envelope'],
}, '_site/static/font/fontawesome/webfonts'); solid: [
'globe',
'circle-arrow-right',
'pencil',
'infinity',
'download',
'code-commit',
],
},
'_site/static/font/fontawesome/webfonts',
);
eleventyConfig.addPlugin(i18n, { eleventyConfig.addPlugin(i18n, {
translations, translations,
fallbackLocales: { fallbackLocales: {
'*': 'en-US' '*': 'en-US',
} },
}); });
eleventyConfig.addFilter("baseUrl", (text) => { eleventyConfig.addFilter('baseUrl', (text) => {
return text.replace(/(?:ru)\//g, ""); return text.replace(/(?:ru)\//g, '');
}); });
eleventyConfig.addFilter("i18n_locale", (current_locale, locale_list) => { eleventyConfig.addFilter('i18n_locale', (current_locale, locale_list) => {
return locale_list.filter((x) => {
return x.code === (current_locale ?? 'en-US');
})[0].label;
});
return locale_list.filter(x => {return x.code === (current_locale ?? "en-US")})[0].label; eleventyConfig.addFilter('i18n_urls', (page, all) => {
}) var locale_urls = locales
.map((x) => {
if (x.url != '') return x.url;
})
.filter((x) => {
return x !== undefined;
});
eleventyConfig.addFilter("i18n_urls", (page, all) => { var split_url = page.split('/').length > 1 ? page.split('/')[1] : '';
var locale_urls = locales.map((x => { if (x.url != "") return x.url })).filter(x => {return x !== undefined});
var split_url = page.split('/').length > 1 ? page.split('/')[1] : "";
// find the current locale // find the current locale
var active_local = ""; var active_local = '';
locale_urls.forEach(locale => { locale_urls.forEach((locale) => {
if(locale === split_url){ if (locale === split_url) {
active_local = locale active_local = locale;
return true; return true;
} }
return false return false;
}) });
// get remaining locales // get remaining locales
var remaining_locals = locales.map((x => { return x.url })).filter(x => {return x !== active_local}); var remaining_locals = locales
.map((x) => {
return x.url;
})
.filter((x) => {
return x !== active_local;
});
var i18n_pages = [] var i18n_pages = [];
var valid_urls = all.map(x => {return x.url}) var valid_urls = all.map((x) => {
return x.url;
});
remaining_locals.forEach(x => { remaining_locals.forEach((x) => {
var new_url = ("/" + page.replace(active_local,x)).replace(/\/{2,}/,"/"); var new_url = ('/' + page.replace(active_local, x)).replace(
if (valid_urls.indexOf(new_url) !== -1){ /\/{2,}/,
'/',
);
if (valid_urls.indexOf(new_url) !== -1) {
i18n_pages.push({ i18n_pages.push({
"url": new_url, url: new_url,
"meta": locales.filter(y => {return y.url === x})[0] meta: locales.filter((y) => {
}) return y.url === x;
})[0],
});
} }
}) });
return i18n_pages return i18n_pages;
}); });
return { return {
dir: { dir: {
input: "src", input: 'src',
formats: "njk", formats: 'njk',
includes: "_includes", includes: '_includes',
data: "_data", data: '_data',
output: "_site" output: '_site',
}, },
templateFormats: ["md", "html", "njk", "11ty.js"], templateFormats: ['md', 'html', 'njk', '11ty.js'],
htmlTemplateEngine: "njk", htmlTemplateEngine: 'njk',
markdownTemplateEngine: "njk", markdownTemplateEngine: 'njk',
passthroughFileCopy: true passthroughFileCopy: true,
}; };
}; };

View file

@ -1,5 +1,4 @@
const path = require('path'); const generateContentHash = require('../lib/generate-content-hash.js');
const generateContentHash = require('../lib/generateContentHash');
const hash = generateContentHash('src/static/**/*.{scss,css}'); const hash = generateContentHash('src/static/**/*.{scss,css}');

View file

@ -1,5 +1,5 @@
module.exports = { module.exports = {
type: (data) => 'page', type: 'page',
meta: { meta: {
site: { site: {
name: (data) => data.site.title, name: (data) => data.site.title,
@ -9,7 +9,7 @@ module.exports = {
src: (data) => data.site.image, src: (data) => data.site.image,
}, },
}, },
language: (data) => 'en-US', language: 'en-US',
url: (data) => data.site.url + data.page.url, url: (data) => data.site.url + data.page.url,
title: (data) => data.title || data.site.title, title: (data) => data.title || data.site.title,
description: (data) => data.description || data.site.description, description: (data) => data.description || data.site.description,

View file

@ -9,7 +9,7 @@ module.exports = {
ru: 'Программа проверки и форматирования шаблонов HTML', ru: 'Программа проверки и форматирования шаблонов HTML',
fr: 'Linter et formateur de modèles HTML', fr: 'Linter et formateur de modèles HTML',
}, },
// lang_name: { // Lang_name: {
// 'en-US': "English", // 'en-US': "English",
// ru: "Русский" // ru: "Русский"
// }, // },
@ -23,14 +23,14 @@ module.exports = {
fr: '/fr', fr: '/fr',
}, },
next_release: { next_release: {
'en-US': "Next Release", 'en-US': 'Next Release',
ru: "Следующая публикация", ru: 'Следующая публикация',
fr: 'Prochaine Version' fr: 'Prochaine Version',
}, },
getting_started: { getting_started: {
'en-US': 'Getting Started', 'en-US': 'Getting Started',
ru: 'Начало Работы', ru: 'Начало Работы',
fr: 'Commencer' fr: 'Commencer',
}, },
formatter: { formatter: {
'en-US': 'Formatter', 'en-US': 'Formatter',
@ -40,7 +40,7 @@ module.exports = {
linter: { linter: {
'en-US': 'Linter', 'en-US': 'Linter',
ru: 'Линтер', ru: 'Линтер',
fr: 'Linter' fr: 'Linter',
}, },
configuration: { configuration: {
'en-US': 'Configuration', 'en-US': 'Configuration',
@ -61,12 +61,12 @@ module.exports = {
'en-US': 'en-US':
'Find common syntax errors, reformat to make your HTML templates shine! Supports django, jinja, nunjucks, twig, handlebars, mustache, golang, and more!', 'Find common syntax errors, reformat to make your HTML templates shine! Supports django, jinja, nunjucks, twig, handlebars, mustache, golang, and more!',
ru: 'Найдите распространенные синтаксические ошибки, переформатируйте, чтобы ваши HTML-шаблоны сияли! Поддерживает django, jinja, nunjucks, twig, handlebars, mustache, golang и многое другое!', ru: 'Найдите распространенные синтаксические ошибки, переформатируйте, чтобы ваши HTML-шаблоны сияли! Поддерживает django, jinja, nunjucks, twig, handlebars, mustache, golang и многое другое!',
fr: 'Trouvez les erreurs de syntaxe courantes, reformatez pour faire briller vos modèles HTML ! Supporte django, jinja, nunjucks, twig, handlebars, mustache, golang, et plus encore !' fr: 'Trouvez les erreurs de syntaxe courantes, reformatez pour faire briller vos modèles HTML ! Supporte django, jinja, nunjucks, twig, handlebars, mustache, golang, et plus encore !',
}, },
updated: { updated: {
'en-US': 'Updated', 'en-US': 'Updated',
ru: 'Обновлен', ru: 'Обновлен',
fr: 'Actualisé' fr: 'Actualisé',
}, },
changelog: { changelog: {
'en-US': 'Changelog', 'en-US': 'Changelog',
@ -81,13 +81,13 @@ module.exports = {
index_title: { index_title: {
'en-US': 'Lint & Format HTML Templates', 'en-US': 'Lint & Format HTML Templates',
ru: 'Проверка и форматирование html-шаблонов', ru: 'Проверка и форматирование html-шаблонов',
fr: 'Lint & Format Templates HTML' fr: 'Lint & Format Templates HTML',
}, },
index_description: { index_description: {
'en-US': 'en-US':
'Once upon a time all the other programming languages had a formatter and linter. Css, javascript, python, the c suite, typescript, ruby, php, go, swift, and you know the others. <i>The cool kids on the block.</i><br>HTML templates were left out there on their own, in the cold, unformatted and unlinted :( The dirty corner in your repository. <i>Something had to change.</i><br>Welcome djLint, the free cleaning service for html templates!<br>And the html templates lived happily ever after.', 'Once upon a time all the other programming languages had a formatter and linter. Css, javascript, python, the c suite, typescript, ruby, php, go, swift, and you know the others. <i>The cool kids on the block.</i><br>HTML templates were left out there on their own, in the cold, unformatted and unlinted :( The dirty corner in your repository. <i>Something had to change.</i><br>Welcome djLint, the free cleaning service for html templates!<br>And the html templates lived happily ever after.',
ru: 'Когда-то давно все другие языки программирования имели форматтер и линтер. Css, javascript, python, c suite, typescript, ruby, php, go, swift, и вы знаете другие. <i>Крутые ребята в квартале.</i><br>HTML-шаблоны остались там сами по себе, на холоде, неформатированные и нелинкованные :( Грязный угол в вашем репозитории. <i>Что-то должно было измениться.</i><br>Добро пожаловать djLint, бесплатный сервис очистки html-шаблонов!<br>И html-шаблоны жили долго и счастливо.', ru: 'Когда-то давно все другие языки программирования имели форматтер и линтер. Css, javascript, python, c suite, typescript, ruby, php, go, swift, и вы знаете другие. <i>Крутые ребята в квартале.</i><br>HTML-шаблоны остались там сами по себе, на холоде, неформатированные и нелинкованные :( Грязный угол в вашем репозитории. <i>Что-то должно было измениться.</i><br>Добро пожаловать djLint, бесплатный сервис очистки html-шаблонов!<br>И html-шаблоны жили долго и счастливо.',
fr: 'Il était une fois, un royaume où tous les autres langages de programmation avaient un formateur et un linter. Css, javascript, python, la suite c, typescript, ruby, php, go, swift, et vous connaissez les autres. <i>Les gamins cool du quartier.</i><br>Les modèles HTML restaient là, seuls, dans le froid, non formatés et non non-lintés :( Le coin cracra de votre entrepôt. <i>Quelque chose devait changer.</i><br>Bienvenue à djLint, le service gratuit de nettoyage des modèles html !<br>Et les modèles html vécurent heureux jusqu\'à la fin des temps.', fr: "Il était une fois, un royaume où tous les autres langages de programmation avaient un formateur et un linter. Css, javascript, python, la suite c, typescript, ruby, php, go, swift, et vous connaissez les autres. <i>Les gamins cool du quartier.</i><br>Les modèles HTML restaient là, seuls, dans le froid, non formatés et non non-lintés :( Le coin cracra de votre entrepôt. <i>Quelque chose devait changer.</i><br>Bienvenue à djLint, le service gratuit de nettoyage des modèles html !<br>Et les modèles html vécurent heureux jusqu'à la fin des temps.",
}, },
index_fav_lang: { index_fav_lang: {
'en-US': 'find your favorite template language!', 'en-US': 'find your favorite template language!',
@ -123,7 +123,7 @@ module.exports = {
'en-US': 'en-US':
'Contributions are welcome. Send a pr with a new feature, or checkout the <a href="https://github.com/Riverside-Healthcare/djlint/issues">issue</a> list and help where you can.', 'Contributions are welcome. Send a pr with a new feature, or checkout the <a href="https://github.com/Riverside-Healthcare/djlint/issues">issue</a> list and help where you can.',
ru: 'Вклад в работу сайта приветствуется. Пришлите письмо с новой функцией или ознакомьтесь со <a href="https://github.com/Riverside-Healthcare/djlint/issues">списком проблем</a> и помогите, чем можете.', ru: 'Вклад в работу сайта приветствуется. Пришлите письмо с новой функцией или ознакомьтесь со <a href="https://github.com/Riverside-Healthcare/djlint/issues">списком проблем</a> и помогите, чем можете.',
fr: 'Les contributions sont les bienvenues. Envoyez un pr avec une nouvelle fonctionnalité, ou consultez la <a href="https://github.com/Riverside-Healthcare/djlint/issues">liste</a> et aidez où vous pouvez.' fr: 'Les contributions sont les bienvenues. Envoyez un pr avec une nouvelle fonctionnalité, ou consultez la <a href="https://github.com/Riverside-Healthcare/djlint/issues">liste</a> et aidez où vous pouvez.',
}, },
edit_page: { edit_page: {
'en-US': 'Edit this page', 'en-US': 'Edit this page',
@ -134,5 +134,5 @@ module.exports = {
'en-US': 'Ignoring Code', 'en-US': 'Ignoring Code',
ru: 'Игнорирование Контент', ru: 'Игнорирование Контент',
fr: 'Ignorer le Contenu', fr: 'Ignorer le Contenu',
} },
}; };

View file

@ -1,5 +1,4 @@
const path = require('path'); const generateContentHash = require('../lib/generate-content-hash.js');
const generateContentHash = require('../lib/generateContentHash');
const hash = generateContentHash('src/static/js/**/*.js'); const hash = generateContentHash('src/static/js/**/*.js');

View file

@ -13,5 +13,5 @@ module.exports = [
label: 'Français', label: 'Français',
code: 'fr', code: 'fr',
url: 'fr', url: 'fr',
} },
]; ];

View file

@ -2,12 +2,13 @@ const htmlmin = require('html-minifier');
module.exports = function (content, outputPath) { module.exports = function (content, outputPath) {
if (outputPath.endsWith('.html')) { if (outputPath.endsWith('.html')) {
let minified = htmlmin.minify(content, { const minified = htmlmin.minify(content, {
useShortDoctype: true, useShortDoctype: true,
removeComments: true, removeComments: true,
collapseWhitespace: true, collapseWhitespace: true,
}); });
return minified; return minified;
} }
return content; return content;
}; };

View file

@ -1,6 +1,6 @@
const esbuild = require('esbuild'); const esbuild = require('esbuild');
const generateContentHash = require('../lib/generate-content-hash.js');
const generateContentHash = require('../lib/generateContentHash');
module.exports = class { module.exports = class {
data() { data() {
return { return {

View file

@ -1,9 +1,10 @@
const util = require('util'); const { promisify } = require('util');
const sass = require('sass'); // `npm i -D sass` const sass = require('sass');
const renderSass = util.promisify(sass.render); // `npm i -D sass`
const renderSass = promisify(sass.render);
const purgecss = require('@fullhuman/postcss-purgecss'); const purgecss = require('@fullhuman/postcss-purgecss');
const postcss = require('postcss'); const postcss = require('postcss');
const generateContentHash = require('../lib/generateContentHash'); const generateContentHash = require('../lib/generate-content-hash.js');
module.exports = class { module.exports = class {
async data() { async data() {
@ -20,7 +21,7 @@ module.exports = class {
file: 'src/static/css/site.scss', file: 'src/static/css/site.scss',
}); });
return await postcss([ return postcss([
require('postcss-nested'), require('postcss-nested'),
purgecss({ purgecss({
content: ['./src/**/*.njk', './src/**/*.md', './src/**/*.js'], content: ['./src/**/*.njk', './src/**/*.md', './src/**/*.js'],

View file

@ -16,7 +16,7 @@ This pattern is recommended:
```html ```html
<div class="class1 {% if condition -%}class2{%- endif %}">content</div> <div class="class1 {% if condition -%}class2{%- endif %}">content</div>
^ space here ^ space here
``` ```
{% endraw %} {% endraw %}

View file

@ -11,24 +11,32 @@ keywords: template linter, template formatter, djLint, HTML, templates, formatte
Changelog is now included in the [release](https://github.com/Riverside-Healthcare/djLint/releases). Changelog is now included in the [release](https://github.com/Riverside-Healthcare/djLint/releases).
<!--## {{ "next_release" i18n }}--> <!--## {{ "next_release" i18n }}-->
## 1.0.2 ## 1.0.2
::: content ::: content
- Bug fixes [#240](https://github.com/Riverside-Healthcare/djLint/issues/240) - Bug fixes [#240](https://github.com/Riverside-Healthcare/djLint/issues/240)
::: :::
## 1.0.1 ## 1.0.1
::: content ::: content
- Bug fixes [#236](https://github.com/Riverside-Healthcare/djLint/issues/236) - Bug fixes [#236](https://github.com/Riverside-Healthcare/djLint/issues/236)
::: :::
## 1.0.0 ## 1.0.0
::: content ::: content
- Bug fixes [#224](https://github.com/Riverside-Healthcare/djLint/issues/224) - Bug fixes [#224](https://github.com/Riverside-Healthcare/djLint/issues/224)
::: :::
## 0.7.6 ## 0.7.6
::: content ::: content
- Bug fixes [#189](https://github.com/Riverside-Healthcare/djLint/issues/189), [#197](https://github.com/Riverside-Healthcare/djLint/issues/189) - Bug fixes [#189](https://github.com/Riverside-Healthcare/djLint/issues/189), [#197](https://github.com/Riverside-Healthcare/djLint/issues/189)
- Added `--warn` flag to return return errors as warnings. - Added `--warn` flag to return return errors as warnings.
::: :::
@ -38,11 +46,11 @@ Changelog is now included in the [release](https://github.com/Riverside-Healthca
::: content ::: content
- Bug fixes [#187](https://github.com/Riverside-Healthcare/djLint/issues/187) - Bug fixes [#187](https://github.com/Riverside-Healthcare/djLint/issues/187)
- Added better support for ``yaml`` front matter in template files - Added better support for `yaml` front matter in template files
- Added rule T032 for [#123](https://github.com/Riverside-Healthcare/djLint/issues/123) - Added rule T032 for [#123](https://github.com/Riverside-Healthcare/djLint/issues/123)
- Added rule H033 for [#124](https://github.com/Riverside-Healthcare/djLint/issues/124) - Added rule H033 for [#124](https://github.com/Riverside-Healthcare/djLint/issues/124)
- Changed linter profiles to be inclusive vs exclusive for [#178](https://github.com/Riverside-Healthcare/djLint/issues/178) - Changed linter profiles to be inclusive vs exclusive for [#178](https://github.com/Riverside-Healthcare/djLint/issues/178)
- Added alternate config file option ``.djlintrc`` for [#188](https://github.com/Riverside-Healthcare/djLint/issues/188) - Added alternate config file option `.djlintrc` for [#188](https://github.com/Riverside-Healthcare/djLint/issues/188)
::: :::
## 0.7.4 ## 0.7.4

View file

@ -8,13 +8,14 @@ keywords: template linter, template formatter, djLint, HTML, templates, formatte
Configuration is done either through your projects `pyproject.toml` file, or a `.djlintrc` file. Command line args will always override any settings in `pyproject.toml`. Configuration is done either through your projects `pyproject.toml` file, or a `.djlintrc` file. Command line args will always override any settings in `pyproject.toml`.
The format for ``pyproject.toml`` is ``toml``. The format for `pyproject.toml` is `toml`.
```ini ```ini
[tool.djlint] [tool.djlint]
<config options> <config options>
``` ```
The format for ``.djlintrc`` is ``json``.
The format for `.djlintrc` is `json`.
```json ```json
{ {
@ -329,7 +330,8 @@ For example, with this option enabled, the following html will be acceptable:
```html ```html
{% raw %} {% raw %}
<input class="{% if this %} <input
class="{% if this %}
then something neat then something neat
{% else %} {% else %}
that is long stuff asdf and more even that is long stuff asdf and more even
@ -344,12 +346,13 @@ Customize order of output message. Default="{code} {line} {message} {match}". If
Optional variables: Optional variables:
::: content ::: content
- `{filename}` - `{filename}`
- `{line}` - `{line}`
- `{code}` - `{code}`
- `{message}` - `{message}`
- `{match}` - `{match}`
::: :::
Usage: Usage:

View file

@ -14,6 +14,12 @@ djLint is build with [Python 3.7+](https://python.org), it can be installed by s
pip install djlint pip install djlint
``` ```
_Or with the npm experimental install - Note, this requires python and pip to be on your system path._
```bash
npm i djlint
```
## CLI Usage ## CLI Usage
djLint is a command line application. See `configuration` for advanced configuration. djLint is a command line application. See `configuration` for advanced configuration.

View file

@ -50,25 +50,26 @@ or as a golang style comment -
Specific linter rules can also be ignored by adding the rule name into the ignored block opening tag. Specific linter rules can also be ignored by adding the rule name into the ignored block opening tag.
{% raw %} {% raw %}
```html ```html
{# djlint:off H025,H026 #} {# djlint:off H025,H026 #}
<p> <p>
{# djlint:on #} {# djlint:on #}
<!-- djlint:off H025--> <!-- djlint:off H025-->
<p> </p>
<!-- djlint:on -->
{% comment %} djlint:off H025 {% endcomment %}
<p> <p>
{% comment %} djlint:on {% endcomment %} <!-- djlint:on -->
{{!-- djlint:off H025 --}} {% comment %} djlint:off H025 {% endcomment %}
<p> </p>
{{!-- djlint:on --}}
{{ /* djlint:off H025 */ }} <p>{% comment %} djlint:on {% endcomment %} {{!-- djlint:off H025 --}}</p>
<p>
{{ /* djlint:on */ }} <p>{{!-- djlint:on --}} {{ /* djlint:off H025 */ }}</p>
<p>{{ /* djlint:on */ }}</p>
``` ```
{% endraw %} {% endraw %}

View file

@ -72,21 +72,21 @@ Ensure djLint is installed in your global python, or on your `PATH`.
- [Marketplace page](https://marketplace.visualstudio.com/items?itemName=monosans.djlint) - [Marketplace page](https://marketplace.visualstudio.com/items?itemName=monosans.djlint)
- [GitHub repository](https://github.com/monosans/djlint-vscode) - [GitHub repository](https://github.com/monosans/djlint-vscode)
::: :::
## neovim ## neovim
djLint can use used as formatter in neovim using the ``null-ls`` plugin. djLint can use used as formatter in neovim using the `null-ls` plugin.
::: content ::: content
- [GitHub repository](https://github.com/jose-elias-alvarez/null-ls.nvim/) - [GitHub repository](https://github.com/jose-elias-alvarez/null-ls.nvim/)
- [Config example](https://github.com/shaeinst/roshnivim/blob/5d991fcfa1b8f865f9653a98c6d97a829d4a2add/lua/plugins/null-ls_nvim.lua#L84-L91) - [Config example](https://github.com/shaeinst/roshnivim/blob/5d991fcfa1b8f865f9653a98c6d97a829d4a2add/lua/plugins/null-ls_nvim.lua#L84-L91)
::: :::
## coc.nvim ## coc.nvim
::: content ::: content
- [npm package](https://www.npmjs.com/package/coc-htmldjango) - [npm package](https://www.npmjs.com/package/coc-htmldjango)
::: :::

View file

@ -16,7 +16,7 @@ Ce modèle est recommandé :
```html ```html
<div class="class1 {% if condition -%}class2{%- endif %}">contenu</div> <div class="class1 {% if condition -%}class2{%- endif %}">contenu</div>
^ espace ici ^ espace ici
``` ```
{% endraw %} {% endraw %}
@ -27,7 +27,7 @@ Ce modèle n'est pas recommandé :
```html ```html
<div class="class1{% if condition -%} class2{%- endif %}">contenu</div> <div class="class1{% if condition -%} class2{%- endif %}">contenu</div>
^ espace ici ^ espace ici
``` ```
{% endraw %} {% endraw %}
@ -43,8 +43,10 @@ Ce modèle est recommandé :
{% raw %} {% raw %}
```html ```html
<input value="{% if database -%}{{ database.name }}{%- else -%}blah{%- endif %}" /> <input
^ ^ ^ ^ -- tags sans espace value="{% if database -%}{{ database.name }}{%- else -%}blah{%- endif %}"
/>
^ ^ ^ ^ -- tags sans espace
``` ```
{% endraw %} {% endraw %}

View file

@ -11,24 +11,32 @@ keywords: template linter, template formatter, djLint, HTML, templates, formatte
Changelog est maintenant inclus dans la [release](https://github.com/Riverside-Healthcare/djLint/releases). Changelog est maintenant inclus dans la [release](https://github.com/Riverside-Healthcare/djLint/releases).
<!--## {{ "next_release" i18n }}--> <!--## {{ "next_release" i18n }}-->
## 1.0.2 ## 1.0.2
::: content ::: content
- Correction de bugs [#240](https://github.com/Riverside-Healthcare/djLint/issues/240) - Correction de bugs [#240](https://github.com/Riverside-Healthcare/djLint/issues/240)
::: :::
## 1.0.1 ## 1.0.1
::: content ::: content
- Correction de bugs [#236](https://github.com/Riverside-Healthcare/djLint/issues/236) - Correction de bugs [#236](https://github.com/Riverside-Healthcare/djLint/issues/236)
::: :::
## 1.0.0 ## 1.0.0
::: content ::: content
- Correction de bugs [#224](https://github.com/Riverside-Healthcare/djLint/issues/224) - Correction de bugs [#224](https://github.com/Riverside-Healthcare/djLint/issues/224)
::: :::
## 0.7.6 ## 0.7.6
::: content ::: content
- Correction de bugs [#189](https://github.com/Riverside-Healthcare/djLint/issues/189), [#197](https://github.com/Riverside-Healthcare/djLint/issues/189) - Correction de bugs [#189](https://github.com/Riverside-Healthcare/djLint/issues/189), [#197](https://github.com/Riverside-Healthcare/djLint/issues/189)
- Ajouté le drapeau `--warn` pour retourner les erreurs de retour comme des avertissements. - Ajouté le drapeau `--warn` pour retourner les erreurs de retour comme des avertissements.
::: :::
@ -38,11 +46,11 @@ Changelog est maintenant inclus dans la [release](https://github.com/Riverside-H
::: content ::: content
- Correction de bugs [#187](https://github.com/Riverside-Healthcare/djLint/issues/187) - Correction de bugs [#187](https://github.com/Riverside-Healthcare/djLint/issues/187)
- Ajout d'une meilleure prise en charge de la matière première ``yaml`` dans les fichiers modèles - Ajout d'une meilleure prise en charge de la matière première `yaml` dans les fichiers modèles
- Ajouté la règle T032 pour [#123](https://github.com/Riverside-Healthcare/djLint/issues/123) - Ajouté la règle T032 pour [#123](https://github.com/Riverside-Healthcare/djLint/issues/123)
- Ajouté la règle H033 pour [#124](https://github.com/Riverside-Healthcare/djLint/issues/124) - Ajouté la règle H033 pour [#124](https://github.com/Riverside-Healthcare/djLint/issues/124)
- Modification des profils des liners pour qu'ils soient inclusifs et non exclusifs pour [#178](https://github.com/Riverside-Healthcare/djLint/issues/178) - Modification des profils des liners pour qu'ils soient inclusifs et non exclusifs pour [#178](https://github.com/Riverside-Healthcare/djLint/issues/178)
- Ajout d'une option alternative pour le fichier de configuration ``.djlintrc``. pour [#188](https://github.com/Riverside-Healthcare/djLint/issues/188) - Ajout d'une option alternative pour le fichier de configuration `.djlintrc`. pour [#188](https://github.com/Riverside-Healthcare/djLint/issues/188)
::: :::
## 0.7.4 ## 0.7.4

View file

@ -8,17 +8,18 @@ keywords: template linter, template formatter, djLint, HTML, templates, formatte
La configuration se fait soit à travers le fichier `pyproject.toml` de votre projet, soit à travers un fichier `.djlintrc`. Les arguments de la ligne de commande remplaceront toujours les paramètres du fichier `pyproject.toml`. La configuration se fait soit à travers le fichier `pyproject.toml` de votre projet, soit à travers un fichier `.djlintrc`. Les arguments de la ligne de commande remplaceront toujours les paramètres du fichier `pyproject.toml`.
Le format du fichier ``pyproject.toml`` est ``toml``. Le format du fichier `pyproject.toml` est `toml`.
```ini ```ini
[tool.djlint] [tool.djlint]
<options de configuration> <options de configuration>
``` ```
Le format du fichier ``djlintrc`` est ``json``.
Le format du fichier `djlintrc` est `json`.
```json ```json
{ {
"option" : "valeur" "option": "valeur"
} }
``` ```
@ -38,7 +39,7 @@ ignore="H014,H015"
```json ```json
{ {
"ignore" : "H014,H015" "ignore": "H014,H015"
} }
``` ```
@ -86,7 +87,6 @@ custom_blocks="toc,example"
Permet d'indenter les balises HTML personnalisées. Par exemple, `<mjml>` ou `<simple-greeting>` ou `<mj-\w+>`. Permet d'indenter les balises HTML personnalisées. Par exemple, `<mjml>` ou `<simple-greeting>` ou `<mj-\w+>`.
Utilisation: Utilisation:
**pyproject.toml** **pyproject.toml**
@ -182,6 +182,7 @@ blank_line_after_tag="load,extends,include"
"blank_line_after_tag": "load,extends,include" "blank_line_after_tag": "load,extends,include"
} }
``` ```
## profile ## profile
Définissez un profil pour la langue du modèle. Le profil activera les règles de linter qui s'appliquent à votre langage de modèle, et peut également changer le reformatage. Par exemple, dans `handlebars`, il n'y a pas d'espaces dans les balises {% raw %}`{{#if}}`{% endraw %}. Définissez un profil pour la langue du modèle. Le profil activera les règles de linter qui s'appliquent à votre langage de modèle, et peut également changer le reformatage. Par exemple, dans `handlebars`, il n'y a pas d'espaces dans les balises {% raw %}`{{#if}}`{% endraw %}.
@ -329,7 +330,8 @@ Par exemple, avec cette option activée, le html suivant sera acceptable :
```html ```html
{% raw %} {% raw %}
<input class="{% if this %} <input
class="{% if this %}
then something neat then something neat
{% else %} {% else %}
that is long stuff asdf and more even that is long stuff asdf and more even
@ -344,12 +346,13 @@ Personnalise l'ordre du message de sortie. Défaut="{code} {ligne} {message} {ma
Variables facultatives : Variables facultatives :
::: content ::: content
- `{filename}` - `{filename}`
- `{line}` - `{line}`
- `{code}` - `{code}`
- `{message}` - `{message}`
- `{match}` - `{match}`
::: :::
Utilisation: Utilisation:
@ -393,7 +396,6 @@ preserve_leading_space=true
} }
``` ```
## preserve_blank_lines ## preserve_blank_lines
Préserve les blancs lorsque cela est possible. Idéal pour les fichiers de modèles non-html où les lignes vides sont intentionnelles. Préserve les blancs lorsque cela est possible. Idéal pour les fichiers de modèles non-html où les lignes vides sont intentionnelles.

View file

@ -38,7 +38,6 @@ djlint . --reformat
"djLint n'est pas un analyseur html ou un validateur de syntaxe." "djLint n'est pas un analyseur html ou un validateur de syntaxe."
%} %}
## Voici un exemple ! ## Voici un exemple !
### Avant ### Avant

View file

@ -14,6 +14,12 @@ djLint est construit avec [Python 3.7+](https://python.org), il peut être insta
pip install djlint pip install djlint
``` ```
_Ou avec l'installation expérimentale npm - Note, ceci requiert que python et pip soient dans votre chemin système._
```bash
npm i djlint
```
## Utilisation de l'interface CLI ## Utilisation de l'interface CLI
djLint est une application en ligne de commande. Voir `configuration` pour une configuration avancée. djLint est une application en ligne de commande. Voir `configuration` pour une configuration avancée.

View file

@ -50,25 +50,26 @@ ou comme un commentaire de style golang -
Des règles spécifiques de linter peuvent également être ignorées en ajoutant le nom de la règle dans la balise d'ouverture du bloc ignoré. Des règles spécifiques de linter peuvent également être ignorées en ajoutant le nom de la règle dans la balise d'ouverture du bloc ignoré.
{% raw %} {% raw %}
```html ```html
{# djlint:off H025,H026 #} {# djlint:off H025,H026 #}
<p> <p>
{# djlint:on #} {# djlint:on #}
<!-- djlint:off H025--> <!-- djlint:off H025-->
<p> </p>
<!-- djlint:on -->
{% comment %} djlint:off H025 {% endcomment %}
<p> <p>
{% comment %} djlint:on {% endcomment %} <!-- djlint:on -->
{{!-- djlint:off H025 --}} {% comment %} djlint:off H025 {% endcomment %}
<p> </p>
{{!-- djlint:on --}}
{{ /* djlint:off H025 */ }} <p>{% comment %} djlint:on {% endcomment %} {{!-- djlint:off H025 --}}</p>
<p>
{{ /* djlint:on */ }} <p>{{!-- djlint:on --}} {{ /* djlint:off H025 */ }}</p>
<p>{{ /* djlint:on */ }}</p>
``` ```
{% endraw %} {% endraw %}

View file

@ -30,7 +30,6 @@ Le repo fournit de multiples hooks pré-configurés pour des profils djLint spé
Notez que ces hooks prédéfinis sont parfois trop conservateurs dans les entrées qu'ils acceptent (vos templates peuvent utiliser une extension différente) donc pre-commit vous permet explicitement de remplacer n'importe laquelle de ces options prédéfinies. Consultez la [docs pre-commit](https://pre-commit.com/#pre-commit-configyaml---hooks) pour une configuration supplémentaire. Notez que ces hooks prédéfinis sont parfois trop conservateurs dans les entrées qu'ils acceptent (vos templates peuvent utiliser une extension différente) donc pre-commit vous permet explicitement de remplacer n'importe laquelle de ces options prédéfinies. Consultez la [docs pre-commit](https://pre-commit.com/#pre-commit-configyaml---hooks) pour une configuration supplémentaire.
### Exemple de Django par défaut ### Exemple de Django par défaut
```yaml ```yaml
@ -73,21 +72,21 @@ Assurez-vous que djLint est installé dans votre python global, ou sur votre `PA
- [Page du marché](https://marketplace.visualstudio.com/items?itemName=monosans.djlint) - [Page du marché](https://marketplace.visualstudio.com/items?itemName=monosans.djlint)
- [GitHub dépôt](https://github.com/monosans/djlint-vscode) - [GitHub dépôt](https://github.com/monosans/djlint-vscode)
::: :::
## neovim ## neovim
djLint peut être utilisé comme formateur dans neovim en utilisant le plugin ``null-ls``. djLint peut être utilisé comme formateur dans neovim en utilisant le plugin `null-ls`.
::: content ::: content
- [GitHub dépôt](https://github.com/jose-elias-alvarez/null-ls.nvim/) - [GitHub dépôt](https://github.com/jose-elias-alvarez/null-ls.nvim/)
- [Exemple de configuration](https://github.com/shaeinst/roshnivim/blob/5d991fcfa1b8f865f9653a98c6d97a829d4a2add/lua/plugins/null-ls_nvim.lua#L84-L91) - [Exemple de configuration](https://github.com/shaeinst/roshnivim/blob/5d991fcfa1b8f865f9653a98c6d97a829d4a2add/lua/plugins/null-ls_nvim.lua#L84-L91)
::: :::
## coc.nvim ## coc.nvim
::: content ::: content
- [npm package](https://www.npmjs.com/package/coc-htmldjango) - [npm package](https://www.npmjs.com/package/coc-htmldjango)
::: :::

View file

@ -8,7 +8,6 @@ keywords: template linter, template formatter, djLint, HTML, modèles, formatter
djLint inclut de nombreuses règles pour vérifier le style et la validité de vos modèles. Profitez pleinement du linter en le configurant pour utiliser un profil prédéfini pour la langue du modèle de votre choix. djLint inclut de nombreuses règles pour vérifier le style et la validité de vos modèles. Profitez pleinement du linter en le configurant pour utiliser un profil prédéfini pour la langue du modèle de votre choix.
```bash ```bash
djlint /path/to/templates --lint djlint /path/to/templates --lint
@ -23,7 +22,6 @@ djlint /path/to/this.html.j2 --profile=jinja
<span class="icon is-large"><i class="fas fa-2x fa-circle-arrow-right"></i></span><div class="my-auto ml-3 is-inline-block"><a href="/fr/docs/configuration/">Consultez le guide de configuration pour connaître toutes les options !</a></div> <span class="icon is-large"><i class="fas fa-2x fa-circle-arrow-right"></i></span><div class="my-auto ml-3 is-inline-block"><a href="/fr/docs/configuration/">Consultez le guide de configuration pour connaître toutes les options !</a></div>
</div> </div>
## Règles personnalisées ## Règles personnalisées
Créez un fichier `.djlint_rules.yaml` à côté de votre `pyproject.toml`. Des règles peuvent être ajoutées à ce fichier et djLint les reprendra. Créez un fichier `.djlint_rules.yaml` à côté de votre `pyproject.toml`. Des règles peuvent être ajoutées à ce fichier et djLint les reprendra.
@ -31,11 +29,11 @@ Créez un fichier `.djlint_rules.yaml` à côté de votre `pyproject.toml`. Des
Une bonne règle suit ce modèle : Une bonne règle suit ce modèle :
```yaml ```yaml
- règle : - règle:
name : T001 name: T001
message : Trouver la Trichotillomanie message: Trouver la Trichotillomanie
indicateurs : re.DOTALL|re.I indicateurs: re.DOTALL|re.I
modèles : modèles:
- Trichotillomanie - Trichotillomanie
``` ```
@ -79,7 +77,6 @@ Une bonne règle suit ce modèle :
| T032 | Espace blanc supplémentaire trouvé dans les balises du modèle. | | T032 | Espace blanc supplémentaire trouvé dans les balises du modèle. |
| H033 | Espace supplémentaire dans l'action du formulaire. | | H033 | Espace supplémentaire dans l'action du formulaire. |
### Ajout de règles ### Ajout de règles
Nous accueillons volontiers les pull requests contenant de nouvelles règles ! Nous accueillons volontiers les pull requests contenant de nouvelles règles !

View file

@ -11,24 +11,32 @@ keywords: облицовка шаблонов, форматер шаблонов
Изменения теперь включен в [релиз](https://github.com/Riverside-Healthcare/djLint/releases). Изменения теперь включен в [релиз](https://github.com/Riverside-Healthcare/djLint/releases).
<!--## {{ "next_release" i18n }}--> <!--## {{ "next_release" i18n }}-->
## 1.0.2 ## 1.0.2
::: content ::: content
- Исправления ошибок [#240](https://github.com/Riverside-Healthcare/djLint/issues/240) - Исправления ошибок [#240](https://github.com/Riverside-Healthcare/djLint/issues/240)
::: :::
## 1.0.1 ## 1.0.1
::: content ::: content
- Исправления ошибок [#236](https://github.com/Riverside-Healthcare/djLint/issues/236) - Исправления ошибок [#236](https://github.com/Riverside-Healthcare/djLint/issues/236)
::: :::
## 1.0.0 ## 1.0.0
::: content ::: content
- Исправления ошибок [#224](https://github.com/Riverside-Healthcare/djLint/issues/224) - Исправления ошибок [#224](https://github.com/Riverside-Healthcare/djLint/issues/224)
::: :::
## 0.7.6 ## 0.7.6
::: content ::: content
- Исправления ошибок [#189](https://github.com/Riverside-Healthcare/djLint/issues/189), [#197](https://github.com/Riverside-Healthcare/djLint/issues/189) - Исправления ошибок [#189](https://github.com/Riverside-Healthcare/djLint/issues/189), [#197](https://github.com/Riverside-Healthcare/djLint/issues/189)
- Добавлен флаг `--warn` для возврата ошибок в виде предупреждений. - Добавлен флаг `--warn` для возврата ошибок в виде предупреждений.
::: :::
@ -38,11 +46,11 @@ keywords: облицовка шаблонов, форматер шаблонов
::: content ::: content
- Исправления ошибок [#187](https://github.com/Riverside-Healthcare/djLint/issues/187) - Исправления ошибок [#187](https://github.com/Riverside-Healthcare/djLint/issues/187)
- Добавлена улучшенная поддержка ``yaml`` front matter в файлах шаблонов - Добавлена улучшенная поддержка `yaml` front matter в файлах шаблонов
- Добавлено правило T032 для [#123](https://github.com/Riverside-Healthcare/djLint/issues/123) - Добавлено правило T032 для [#123](https://github.com/Riverside-Healthcare/djLint/issues/123)
- Добавлено правило H033 для [#124](https://github.com/Riverside-Healthcare/djLint/issues/124) - Добавлено правило H033 для [#124](https://github.com/Riverside-Healthcare/djLint/issues/124)
- Изменены профили линтеров, чтобы они были инклюзивными, а не эксклюзивными для [#178](https://github.com/Riverside-Healthcare/djLint/issues/178) - Изменены профили линтеров, чтобы они были инклюзивными, а не эксклюзивными для [#178](https://github.com/Riverside-Healthcare/djLint/issues/178)
- Добавлена альтернативная опция файла конфигурации ``.djlintrc`` для [#188](https://github.com/Riverside-Healthcare/djLint/issues/188) - Добавлена альтернативная опция файла конфигурации `.djlintrc` для [#188](https://github.com/Riverside-Healthcare/djLint/issues/188)
::: :::
## 0.7.4 ## 0.7.4

View file

@ -12,7 +12,8 @@ keywords: облицовка шаблонов, форматер шаблонов
[tool.djlint] [tool.djlint]
<config options> <config options>
``` ```
Формат для ``.djlintrc`` - ``json``.
Формат для `.djlintrc` - `json`.
```json ```json
{ {
@ -179,6 +180,7 @@ blank_line_after_tag="load,extends,include"
"blank_line_after_tag": "load,extends,include" "blank_line_after_tag": "load,extends,include"
} }
``` ```
## profile ## profile
Установите профиль для языка шаблона. Профиль будет включать правила линтера, применимые к языку шаблонов, а также может изменять переформатирование. Например, в `handlebars` нет пробелов внутри тегов {% raw %}`{{#if}}`{% endraw %}. Установите профиль для языка шаблона. Профиль будет включать правила линтера, применимые к языку шаблонов, а также может изменять переформатирование. Например, в `handlebars` нет пробелов внутри тегов {% raw %}`{{#if}}`{% endraw %}.
@ -325,7 +327,8 @@ format_attribute_template_tags=true
```html ```html
{% raw %} {% raw %}
<input class="{% if this %} <input
class="{% if this %}
then something neat then something neat
{% else %} {% else %}
that is long stuff asdf and more even that is long stuff asdf and more even
@ -340,12 +343,13 @@ format_attribute_template_tags=true
Необязательные переменные: Необязательные переменные:
::: content ::: content
- `{filename}` - `{filename}`
- `{line}` - `{line}`
- `{code}` - `{code}`
- `{message}` - `{message}`
- `{match}` - `{match}`
::: :::
Использование: Использование:
@ -389,7 +393,6 @@ preserve_leading_space=true
} }
``` ```
## preserve_blank_lines ## preserve_blank_lines
Сохраняйте пробелы там, где это возможно. Идеально подходит для не-html файлов шаблонов, где пустые строки являются намеренными. Сохраняйте пробелы там, где это возможно. Идеально подходит для не-html файлов шаблонов, где пустые строки являются намеренными.

View file

@ -14,6 +14,12 @@ djLint собирается с [Python 3.7+](https://python.org), он може
pip install djlint pip install djlint
``` ```
_Или с помощью npm экспериментальная установка - Обратите внимание, это требует, чтобы python и pip были в вашем системном пути._
```bash
npm i djlint
```
## Использование CLI ## Использование CLI
djLint - это приложение командной строки. Для расширенной настройки смотрите `конфигурация`. djLint - это приложение командной строки. Для расширенной настройки смотрите `конфигурация`.

View file

@ -50,25 +50,26 @@ date: Last Modified
Определенные правила linter можно игнорировать, добавив имя правила в открывающий тег игнорируемого блока. Определенные правила linter можно игнорировать, добавив имя правила в открывающий тег игнорируемого блока.
{% raw %} {% raw %}
```html ```html
{# djlint:off H025,H026 #} {# djlint:off H025,H026 #}
<p> <p>
{# djlint:on #} {# djlint:on #}
<!-- djlint:off H025--> <!-- djlint:off H025-->
<p> </p>
<!-- djlint:on -->
{% comment %} djlint:off H025 {% endcomment %}
<p> <p>
{% comment %} djlint:on {% endcomment %} <!-- djlint:on -->
{{!-- djlint:off H025 --}} {% comment %} djlint:off H025 {% endcomment %}
<p> </p>
{{!-- djlint:on --}}
{{ /* djlint:off H025 */ }} <p>{% comment %} djlint:on {% endcomment %} {{!-- djlint:off H025 --}}</p>
<p>
{{ /* djlint:on */ }} <p>{{!-- djlint:on --}} {{ /* djlint:off H025 */ }}</p>
<p>{{ /* djlint:on */ }}</p>
``` ```
{% endraw %} {% endraw %}

View file

@ -72,20 +72,21 @@ djLint можно использовать в качестве плагина Su
- [Страница рынка](https://marketplace.visualstudio.com/items?itemName=monosans.djlint) - [Страница рынка](https://marketplace.visualstudio.com/items?itemName=monosans.djlint)
- [GitHub репозиторий](https://github.com/monosans/djlint-vscode) - [GitHub репозиторий](https://github.com/monosans/djlint-vscode)
::: :::
## neovim ## neovim
djLint можно использовать в качестве форматера в neovim с помощью плагина ``null-ls``. djLint можно использовать в качестве форматера в neovim с помощью плагина `null-ls`.
::: content ::: content
- [GitHub репозиторий](https://github.com/jose-elias-alvarez/null-ls.nvim/) - [GitHub репозиторий](https://github.com/jose-elias-alvarez/null-ls.nvim/)
- [Пример конфигурации](https://github.com/shaeinst/roshnivim/blob/5d991fcfa1b8f865f9653a98c6d97a829d4a2add/lua/plugins/null-ls_nvim.lua#L84-L91) - [Пример конфигурации](https://github.com/shaeinst/roshnivim/blob/5d991fcfa1b8f865f9653a98c6d97a829d4a2add/lua/plugins/null-ls_nvim.lua#L84-L91)
::: :::
## coc.nvim ## coc.nvim
::: content ::: content
- [npm package](https://www.npmjs.com/package/coc-htmldjango) - [npm package](https://www.npmjs.com/package/coc-htmldjango)
::: :::

View file

@ -77,7 +77,6 @@ djlint /path/to/this.html.j2 --profile=jinja
| T032 | В тегах шаблона обнаружены лишние пробелы. | | T032 | В тегах шаблона обнаружены лишние пробелы. |
| H033 | В действии формы обнаружен лишний пробел. | | H033 | В действии формы обнаружен лишний пробел. |
### Добавление правил ### Добавление правил
Мы приветствуем запросы с новыми правилами! Мы приветствуем запросы с новыми правилами!

View file

@ -1,4 +1,4 @@
@use "sass:math"; @use 'sass:math';
@import '../../../../node_modules/@fortawesome/fontawesome-free/scss/_functions'; @import '../../../../node_modules/@fortawesome/fontawesome-free/scss/_functions';
@import '../../../../node_modules/@fortawesome/fontawesome-free/scss/_variables'; @import '../../../../node_modules/@fortawesome/fontawesome-free/scss/_variables';

11149
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,8 +1,7 @@
{ {
"name": "djlint", "name": "djlint",
"version": "1.3.0", "version": "0.0.1-beta1.0",
"description": "HTML Template Linter and Formatter", "description": "HTML Template Linter and Formatter",
"private": true,
"main": "./bin/index.js", "main": "./bin/index.js",
"directories": { "directories": {
"doc": "docs", "doc": "docs",
@ -31,16 +30,17 @@
"angular template formatter" "angular template formatter"
], ],
"files": [ "files": [
"src", "bin"
"bin",
"requirements.txt"
], ],
"bin": { "bin": {
"djlint": "./bin/index.js" "djlint": "./bin/index.js"
}, },
"scripts": { "scripts": {
"format": "prettier --config .prettierrc \"{bin,docs}/**/*.{ts,css,less,scss,js,json,md,yaml,html}\" --write",
"postinstall": "node ./bin/install.js", "postinstall": "node ./bin/install.js",
"commit": "git add . && pre-commit run && git add . && cz --no-verify" "pre-commit": "lint-staged",
"commit": "git add . && pre-commit run && git add . && npm run pre-commit && cz --no-verify",
"test": "xo"
}, },
"author": { "author": {
"name": "Christopher Pickering", "name": "Christopher Pickering",
@ -52,6 +52,7 @@
}, },
"homepage": "https://djlint.com", "homepage": "https://djlint.com",
"dependencies": { "dependencies": {
"python-shell": "^3.0.1",
"yargs": "17.4.0" "yargs": "17.4.0"
}, },
"devDependencies": { "devDependencies": {
@ -63,11 +64,36 @@
"@semantic-release/npm": "9.0.1", "@semantic-release/npm": "9.0.1",
"@semantic-release/release-notes-generator": "10.0.3", "@semantic-release/release-notes-generator": "10.0.3",
"cz-conventional-changelog": "3.3.0", "cz-conventional-changelog": "3.3.0",
"semantic-release": "19.0.3" "lint-staged": "^13.0.3",
"semantic-release": "19.0.3",
"xo": "^0.50.0"
}, },
"config": { "config": {
"commitizen": { "commitizen": {
"path": "./node_modules/cz-conventional-changelog" "path": "./node_modules/cz-conventional-changelog"
} }
} },
"lint-staged": {
"{bin,docs}/**/*.{ts,css,less,scss,js,json,md,yaml,html}": [
"npm run format"
]
},
"xo": {
"space": true,
"prettier": true,
"rules": {
"unicorn/prefer-module": "off",
"no-var": "warn",
"camelcase": "warn",
"unicorn/filename-case":"warn",
"unicorn/no-process-exit":"off"
},
"globals": [
"document",
"window",
"data",
"debounce",
"history"
]
}
} }