define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Base
{
public:
static void func()
{
cout << "父類中靜態(tài)func調(diào)用" << endl;
}
static void func(int a)
{
cout << "父類中靜態(tài)func(int a)調(diào)用" << endl;
}
static int m_A; // 靜態(tài)成員變量 // 類內(nèi)聲明
};
int Base::m_A = 10; // 類外賦值
class Son :public Base
{
public:
static void func()
{
cout << "子類中靜態(tài)func調(diào)用" << endl;
}
static int m_A; // 靜態(tài)成員變量 // 類內(nèi)聲明
};
int Son::m_A = 100; // 類外賦值
------------------------------------------------------------------
void test01()
{
Son s1;
// 通過對象訪問靜態(tài)成員變量
cout << s1.m_A << endl; // 結(jié)果: 100
cout << s1.Base::m_A << endl; // 結(jié)果: 10
//通過類名訪問靜態(tài)成員變量
cout << Son::m_A << endl;
cout << Son::Base::m_A << endl;
}
------------------------------------------------------------------
void test02()
{
Son s2;
// 通過對象訪問靜態(tài)成員函數(shù)
s2.func(); // 結(jié)果:子類中靜態(tài)func調(diào)用
s2.Base::func(); // 結(jié)果:父類中靜態(tài)func調(diào)用
s2.Base::func(1); // 結(jié)果:父類中靜態(tài)func(int a)調(diào)用
// 通過類名訪問靜態(tài)成員函數(shù)
Son::func();
Son::Base::func();
Son::Base::func(1);
}
// 注意 Son::Base::func(); 第一個::是通過類名訪問 第二個::是作用域 注意區(qū)別
本篇文章主要講述Unocss的使用和個人使用之后的感想
在此之前還寫過一篇關(guān)于反對在Vue里使用tailwind CSS的一篇文章(主寫Vue的,React等框架中沒有抵抗)。當(dāng)然,當(dāng)時寫那篇文章的時候腦子也有是有點迷糊的,后來被懟的的很慘,不敢吭聲。
近一段時間,公司里給安排了一個新項目,這次我選擇安排上了Unocss+sass來寫樣式。但為什么本身就比較反對在Vue中使用原子化CSS的我,卻在新的項目中使用了Unocss呢?
理由很簡單:主要還是原子化CSS最近被炒的非常熱,前端技術(shù)本來更新的就快,并不是說討厭某一個技術(shù)就要極力去抵抗的(當(dāng)然也不是說討厭,只是覺得Vue的css處理已經(jīng)非常棒了,在Vue中可能不會那么需要一個額外的css框架來支持),還是有就是當(dāng)時說tailwind CSS不適合用在Vue中使用的時候,有部分人說我沒寫過tailwind CSS。哎,我就不寫tailwind CSS我寫Unocss (。?ω?。)
下載安裝Unocss
npm i unocss
或
yarn add unocss
安裝之后為了更好的IDE使用體驗,官方是比較建議創(chuàng)建一個單獨的文件來配置Unocss
在項目的根目錄下創(chuàng)建uno.confin.{js,ts,mjs,mts}文件
//uno.config.ts
import { defineConfig } from "unocss";
export default defineConfig({
//...Unocss的配置項 看下面配置介紹
});
還需要在vite.config.ts中引入一下
//vite.config.ts
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import UnoCss from "unocss/vite";
export default defineConfig(({ command }) => ({
plugins: [
vue(),
//插件中也可以選擇指定uno文件地址 參數(shù){configFile: './uno.config.ts'}
//當(dāng)然默認(rèn)不傳參數(shù)也是可以正常運(yùn)行的 這里就不選擇傳入?yún)?shù)了
UnoCss()
],
//....
})
//另外webpack5中 webpack.config.js
const UnoCSS = require('@unocss/webpack').default
module.exports = {
plugins: [UnoCSS()],
optimization: { realContentHash: true }
}
這樣在uno.config.ts文件中配置好后,就可以寫現(xiàn)在火熱的原子化樣式了
<div class="h-full text-center flex select-none all:transition-400">
<p text-16 px-10 shadow="[0_0_10px_4px_#dedede]">iceCode</p>
</div>
Unocss的配置還是挺多的,但是一般情況下很少全部用到,僅有幾個配置就可以覆蓋大多數(shù)的場景
這個配置主要制定自己樣式的規(guī)則,這個個人覺得可能會有一部分
rules: [
//靜態(tài)規(guī)則 生成 .m-1 { margin: 0.25rem; }的樣式
['m-1', { margin: '0.25rem' }],
//動態(tài)規(guī)則 使用正則表達(dá)式進(jìn)行匹配 可以動態(tài)的進(jìn)行匹配
//m-3 轉(zhuǎn)化成css .m-3 { margin: 0.75rem; } m-100 轉(zhuǎn)化成css .m-100 { margin: 25rem; }
[/^m-(\d+)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
//如果有需要 還可以更高級 當(dāng)然大多數(shù)情況下用不到
[
/^custom-(.+)$/,
([, name], { rawSelector, currentSelector, variantHandlers, theme }) => {
// 丟棄不匹配的規(guī)則
if (name.includes('something')) return
// 如果你想的話,可以禁用這個規(guī)則的變體
if (variantHandlers.length) return
const selector = e(rawSelector)
// 返回一個字符串而不是對象
return `
${selector} {
font-size: ${theme.fontSize.sm};
}
/* 你可以有多條規(guī)則 */
${selector}::after {
content: 'after';
}
.foo > ${selector} {
color: red;
}
/* 或媒體查詢 */
@media (min-width: ${theme.breakpoints.sm}) {
${selector} {
font-size: ${theme.fontSize.sm};
}
}
`
}
]
]
可以自己設(shè)置一些自己的特定場景來指定自己的預(yù)設(shè),當(dāng)然也可以使用Unocss社區(qū)提供的預(yù)設(shè)來進(jìn)行配置
創(chuàng)建要給自己的預(yù)設(shè)
// my-preset.ts
import { Preset } from 'unocss'
export default function myPreset(options: MyPresetOptions): Preset {
return {
name: 'my-preset',
rules: [
// ...
],
variants: [
// ...
]
// 它支持您在根配置中擁有的大多數(shù)配置
}
}
在使用的的時候引入到 presets 中去即可
// unocss.config.ts
import { defineConfig } from 'unocss'
import myPreset from './my-preset'
export default defineConfig({
presets: [
myPreset({
/* 預(yù)設(shè)選項 */
})
]
})
主要還是看個人需求,預(yù)設(shè)這個東西還是用別人制定好的最香。
該預(yù)設(shè)繼承preset-wind和preset-mini兩個預(yù)設(shè)
該預(yù)設(shè)嘗試提供流行的功能優(yōu)先框架(包括 Tailwind CSS、Windi CSS、Bootstrap、Tachyons 等)的共同超集。所以怎么寫規(guī)則怎么使用可以完全按照這些官網(wǎng)上的寫
// uno.config.ts
import { defineConfig,presetUno } from 'unocss'
export default defineConfig({
presets: [presetUno()]
})
例如,ml-3(Tailwind)、ms-2(Bootstrap)、ma4(Tachyons)和 mt-10px(Windi CSS)都是有效的。
.ma4 {
margin: 1rem;
}
.ml-3 {
margin-left: 0.75rem;
}
.ms-2 {
margin-inline-start: 0.5rem;
}
.mt-10px {
margin-top: 10px;
}
使用屬性化預(yù)設(shè)可以更好的簡化模板中css樣的代碼
// uno.config.ts
import { defineConfig,presetUno,presetAttributify } from 'unocss'
export default defineConfig({
presets: [
presetUno(),
presetAttributify()
// ...
]
})
當(dāng)使用tailwind CSS寫一個工具類的按鈕時,過長的樣式就會使項目難以維護(hù)
<button
class="bg-blue-400 hover:bg-blue-500 text-sm text-white
font-mono font-light py-2 px-4 rounded border-2
border-blue-200 dark:bg-blue-500 dark:hover:bg-blue-600"
>
Button
</button>
可以這時屬性化預(yù)設(shè)就可以很大程度上的簡化這些寫作的樣式
//這樣寫 是否清晰很多
<button
bg="blue-400 hover:blue-500 dark:blue-500 dark:hover:blue-600"
text="sm white"
font="mono light"
p="y-2 x-4"
border="2 rounded blue-200"
>
Button
</button>
當(dāng)然也有一般情況下并不會寫這么多樣式在模板上
<button class="border border-red">Button</button>
//還可以這樣使用
<button border="~ red">Button</button>
//也可以拋棄class
<div m-2 rounded text-teal-400 />
可以使用純css圖標(biāo),首先還需要下載icon
npm install -D @iconify/json 也可以只下載 某一個你要使用的圖標(biāo) npm install -D @iconify-json/[the-collection-you-want]
//或者
yarn add @iconify/json 也可以只下載 某一個你要使用的圖標(biāo) yarn add @iconify-json/[the-collection-you-want]
// uno.config.ts
import { defineConfig,presetIcons } from 'unocss'
export default defineConfig({
presets: [
presetIcons({
/* options */
})
// ...other presets
]
})
使用時只需要寫class即可
<!-- Phosphor 圖標(biāo)中的基本錨點圖標(biāo) -->
<div class="i-ph-anchor-simple-thin" />
<!-- 來自 Material Design 圖標(biāo)的橙色鬧鐘 -->
<div class="i-mdi-alarm text-orange-400" />
可以通過配置的provider屬性來使用字體
目前僅支持:
// uno.config.ts
import { defineConfig,presetWebFonts,presetUno } from 'unocss'
export default defineConfig({
presets: [
presetUno(),
presetWebFonts({
provider:'none',
/* options */
})
]
})
UnoCSS 的 TailWind/Windi CSS 預(yù)設(shè)。繼承于preset-mini。
UnoCSS 的基本預(yù)設(shè),僅包含最基本的實用工具。
可以將css樣式作為HTML的標(biāo)簽使用,當(dāng)使用單個樣式的時候會比較好用。
// uno.config.ts
import { defineConfig,presetTagify } from 'unocss'
export default defineConfig({
presets: [
presetTagify({
/* options */
})
// ...other presets
]
})
配置標(biāo)簽預(yù)設(shè)之后,單個樣式可以作為標(biāo)簽使用了
<text-red>red text</text-red>
<flex>flexbox</flex>
<!--可以理解為-->
<span class="text-red">red text</span>
<div class="flex">flexbox</div>
眾所周知,這個css框架使用的都是rem作為單位,如果想要在Unocss中使用px需要寫上固定的px單位,這樣顯得不夠簡潔,這里就可以使用這個預(yù)設(shè)自動轉(zhuǎn)將rem轉(zhuǎn)化為px
這個預(yù)設(shè)不包含在unocss包中,需要單獨的額外下載
npm install -D @unocss/preset-rem-to-px
//或
yarn add -D @unocss/preset-rem-to-px
// uno.config.ts
import { defineConfig } from 'unocss'
import presetRemToPx from '@unocss/preset-rem-to-px'
export default defineConfig({
presets: [
presetRemToPx({
baseFontSize: 4, //基準(zhǔn)字體大小 官方的默認(rèn)預(yù)設(shè)16(1單位 = 0.25rem)所以這里為4 為1:1
})
// ...other presets
]
})
這里在使用樣式的時候,直接寫數(shù)字就是px為單位的樣式
<div class="m-2"></div>
//css
.m-2 {
margin: 2px;
}
Transformers 用于轉(zhuǎn)換源代碼以支持約定。
它提供了一個統(tǒng)一的接口來轉(zhuǎn)換源代碼以支持約定。
// my-transformer.ts
import { createFilter } from '@rollup/pluginutils'
import { SourceCodeTransformer } from 'unocss'
export default function myTransformers(
options: MyOptions = {}
): SourceCodeTransformer {
return {
name: 'my-transformer',
enforce: 'pre', // 在其他transformer之前執(zhí)行
idFilter() {
// 只轉(zhuǎn)換 .tsx 和 .jsx 文件
return id.match(/\.[tj]sx$/)
},
async transform(code, id, { uno }) {
// code 是一個 MagicString 實例
code.appendRight(0, '/* my transformer */')
}
}
}
當(dāng)然,他也有著自己的幾個轉(zhuǎn)換器
為 UnoCSS 啟用 Windi CSS 的 變體組特性。
// uno.config.ts
import { defineConfig,transformerVariantGroup } from 'unocss'
export default defineConfig({
// ...
transformers: [
transformerVariantGroup(),
],
})
啟用這個預(yù)設(shè)的時候,就可以將一些前綴相同的屬性以組的形式來寫
<div class="hover:(bg-gray-400 font-medium) font-(light mono)"/>
//轉(zhuǎn)化為
<div class="hover:bg-gray-400 hover:font-medium font-light font-mono"/>
//個人感覺這種不如上面的 屬性化預(yù)設(shè) 使用屬性化預(yù)設(shè)可以寫成 看個人喜好
<div hover='bg-gray-400 font-medium' font='light mono'/>
啟用指令轉(zhuǎn)換器將支持 @apply、@screen 和 theme() 指令。
// uno.config.ts
import { defineConfig,transformerDirectives } from 'unocss'
export default defineConfig({
// ...
transformers: [
transformerDirectives(),
],
})
.custom-div {
@apply text-center my-0 font-medium;
}
//轉(zhuǎn)化為
.custom-div {
margin-top: 0rem;
margin-bottom: 0rem;
text-align: center;
font-weight: 500;
}
.grid {
--uno: grid grid-cols-2;
}
@screen xs {
.grid {
--uno: grid-cols-1;
}
}
@screen sm {
.grid {
--uno: grid-cols-3;
}
}
//轉(zhuǎn)換為
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@media (min-width: 320px) {
.grid {
grid-template-columns: repeat(1, minmax(0, 1fr));
}
}
@media (min-width: 640px) {
.grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
.btn-blue {
background-color: theme('colors.blue.500');
}
//轉(zhuǎn)化為
.btn-blue {
background-color: #3b82f6;
}
這個轉(zhuǎn)換器可以將寫在一個元素上的樣式編譯成一個類名
// uno.config.ts
import { defineConfig,transformerCompileClass } from 'unocss'
export default defineConfig({
// ...
transformers: [
transformerCompileClass(),
],
})
在類字符串的開頭加上:uno:即可將后面所寫的樣式編譯成一個類名,不支持屬性化預(yù)設(shè)
<div class=":uno: text-center sm:text-left">
<div class=":uno: text-sm font-bold hover:text-red"/>
</div>
<!--將編譯成 -->
<div class="uno-qlmcrp">
<div class="uno-0qw2gr"/>
</div>
//css
.uno-qlmcrp {
text-align: center;
}
.uno-0qw2gr {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
}
.uno-0qw2gr:hover {
--un-text-opacity: 1;
color: rgba(248, 113, 113, var(--un-text-opacity));
}
@media (min-width: 640px) {
.uno-qlmcrp {
text-align: left;
}
}
這個轉(zhuǎn)換器主要作用于 在jsx文件內(nèi)寫 屬性化預(yù)設(shè)的樣式
// uno.config.ts
import { defineConfig, presetAttributify,transformerAttributifyJsx } from 'unocss'
export default defineConfig({
// ...
presets: [
// ...
presetAttributify()//屬性化預(yù)設(shè)
],
transformers: [
transformerAttributifyJsx(), // <--
],
})
如果沒有這個轉(zhuǎn)換器,在jsx中使用屬性化預(yù)設(shè)將會將無值的樣式識別成布爾值
export function Component() {
return (<div text-red text-center text-5xl animate-bounce>
unocss
</div>)
}
//這里將會轉(zhuǎn)換為
export function Component() {
return (
<div text-red="" text-center="" text-5xl="" animate-bounce="">
unocss
</div>
)
}
個人感覺剩下的配置一般情況下都不太能使用的到,也看項目環(huán)境吧。
可以在屬性內(nèi)配置一些原子化樣式的快捷方式,并且可以類似于Rules一樣配置動態(tài)快捷方式。
shortcuts: {
// 使用原子化樣式定義快捷類
'btn': 'py-2 px-4 font-semibold rounded-lg shadow-md',
'btn-green': 'text-white bg-green-500 hover:bg-green-700',
//使用動態(tài)創(chuàng)建快捷方式
[/^btn-(.*)$/, ([, c]) => `bg-${c}-400 text-${c}-100 py-2 px-4 rounded-lg`]
}
UnoCSS 也支持像 Tailwind / Windi 中的主題系統(tǒng)。在用戶級別上,您可以在配置中指定 theme 屬性,它將與默認(rèn)主題進(jìn)行深度合并。
theme: {
// ...
colors: {
'veryCool': '#0000ff', // class="text-very-cool"
'brand': {
'primary': 'hsla(var(--hue, 217), 78%, 51%)', //class="bg-brand-primary"
}
},
}
//在rules中使用
rules: [
[
/^text-(.*)$/,
([, c], { theme }) => {
if (theme.colors[c]) return { color: theme.colors[c] }
}
]
]
允許對現(xiàn)有規(guī)則應(yīng)用一些變化,例如hover:變體
variants: [
// hover:
(matcher) => {
if (!matcher.startsWith('hover:'))
return matcher
return {
// 去掉前綴并將其傳遞給下一個變體和規(guī)則
matcher: matcher.slice(6),
selector: s => `${s}:hover`,
}
}
],
rules: [
[/^m-(\d)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
]
內(nèi)部實現(xiàn)
提取器用于從源代碼中提取工具的使用情況。
默認(rèn)情況下,會使用 extractorSplit 進(jìn)行拆分。該提取器會將源代碼拆分為標(biāo)記,然后直接提供給引擎。
從配置中注入原始 css 作為預(yù)處理。解析的 theme 可用于自定義 css。
preflights: [
{
getCSS: ({ theme }) => `
* {
color: ${theme.colors.gray?.[700] ?? '#333'};
padding: 0;
margin: 0;
}
`
}
]
主要用于css的順序的優(yōu)先級問題,css的順序影響他們的優(yōu)先級,這了可以在自定義樣式時,添加圖層來固定css順序
rules: [
[/^m-(\d)$/, ([, d]) => ({ margin: `${d / 4}rem` }), { layer: 'utilities' }],//添加圖層
// 當(dāng)您省略圖層時,它將是 `default`
['btn', { padding: '4px' }]
]
//也可以在與檢查中調(diào)用預(yù)設(shè)樣式,進(jìn)行圖層設(shè)置
preflights: [
{
layer: 'my-layer',
getCSS: async () => (await fetch('my-style.css')).text()
}
]
圖層自定義
ts
在智能建議在演示平臺和VS Code 擴(kuò)展中可以進(jìn)行定制。針對于智能提示的屬性
autocomplete: {
templates: [
// 主題推斷
'bg-$color/<opacity>',
// 簡寫
'text-<font-size>',
// 邏輯或組合
'(b|border)-(solid|dashed|dotted|double|hidden|none)',
// 常量
'w-half',
],
shorthands: {
// 等同于 `opacity: "(0|10|20|30|40|50|60|70|90|100)"`
'opacity': Array.from({ length: 11 }, (_, i) => i * 10),
'font-size': '(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)',
// 覆蓋內(nèi)置的簡寫
'num': '(0|1|2|3|4|5|6|7|8|9)'
},
extractors: [
// ...extractors
]
}
import {
defineConfig,
presetUno,
presetAttributify,
presetTypography,
presetIcons,
transformerVariantGroup,
transformerAttributifyJsx,
transformerCompileClass,
transformerDirectives,
} from "unocss";
import presetRemToPx from "@unocss/preset-rem-to-px";
export default defineConfig({
//自定義規(guī)則
rules: [[/^bg-?([0123456789abcdef]+)$/i, ([_, rgb]) => ({ background: `#${rgb}` })]],
//預(yù)設(shè)規(guī)則 有前兩個預(yù)設(shè)可以滿足95%以上的需求
presets: [
//此預(yù)設(shè)規(guī)則可以看Tailwind CSS、Windi CSS、Bootstrap、Tachyons官網(wǎng)了解相關(guān)規(guī)則
presetUno(), //m-10 理解為 margin:10rem 或者 m-10px 理解為 margin:10px
presetAttributify(), //歸因模式 bg="blue-400 hover:blue-500 dark:blue-500 dark:hover:blue-600" 背景顏色的簡寫 也可以再元素上不加class 直接寫屬樣式 例如 <div m-2 p-10 bg-000></div>
// presetTypography(), //排版預(yù)設(shè) 詳細(xì)排版看https://unocss.dev/presets/typography#colors 使用這個前兩個必須
// presetIcons(), //css圖標(biāo) 支持圖標(biāo)看 https://icones.js.org/ 需要下載
// 這里看個人需求是否要使用px
presetRemToPx({
baseFontSize: 4, //基準(zhǔn)字體大小 官方的默認(rèn)預(yù)設(shè)(1單位 = 0.25rem) html的字體是16 所以這里為4
}), //默認(rèn)unocss默認(rèn)是rem 轉(zhuǎn)換成 px單位
],
//看個人需求添加轉(zhuǎn)換器
transformers: [
transformerVariantGroup(),
transformerAttributifyJsx(),
transformerCompileClass(),
transformerDirectives()
],
//以下可以按個人需求添加
shortcuts:{},
layers: {},
theme: {},
variants: [],
extractors: [],
preflights:[]
});
問題主要針對 屬性化預(yù)設(shè)的問題,由于 屬性化預(yù)設(shè)的簡潔、書寫方便,大多數(shù)場景下可使用屬性化來寫樣式,但是屬性化存在著一些問題
<div w100% shadow-[0_0_10px_#dedede] bg-#333></div>
以上這些寫法都是會報錯的,屬性中不允許包含%\[]\#等一些特殊符號的,所以包含顏色或者自定義等含有特殊符號無使用屬性化來寫樣式
屬性化支持有值多屬性寫法,可以使用這種形式來寫屬性化樣式,當(dāng)然中寫的還不如直接一個class的好
<div w="100%" shadow="[0_0_10px_#dedede]" bg="#333"></div>
不過當(dāng)一些有著多屬性時,這種寫法較為舒服
<div border="1px solid #dedede" h="[calc(100vh-500px)]" text="16 #000 center"></div>
<!--對比tailwind CSS -->
<div class="border-1 border-solid border-[#dedede] h-[calc(100vh-500px)] text-16 text-[#000] text-center"></div>
另外class和屬性化的負(fù)數(shù)值寫法是不同
<!--這里mb--20 可以理解為 margin-bootom:-20px-->
<p text="24 center #222 hover:color-red-400" fw-800 mb--20>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Explicabo veniam aut esse iure mollitia. Earum omnis aliquid minus porro nulla commodi dignissimos, voluptatem
accusamus cumque reprehenderit, ea nisi perferendis quis.
</p>
<!--如果使用 class 來寫負(fù)值-->
<!--這里寫負(fù)值寫在前面即可 -mb-20 理解為 margin-bootom:-20px-->
<p class="text-24 text-center text-#222 fw-800 hover:text-red-400 -mb-20">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Explicabo veniam aut esse iure mollitia. Earum omnis aliquid minus porro nulla commodi dignissimos, voluptatem
accusamus cumque reprehenderit, ea nisi perferendis quis.
</p>
創(chuàng)建單獨的uno.config.ts文件就是為了在IDE中配合插件使用,在一個頁面中如果這樣寫可能會看著很亂,當(dāng)配合插件之后,會比較清晰明了一些
在應(yīng)用商店直接搜Unocss
安裝完成之后,你頁面中所寫的樣式都會給標(biāo)明出來
另外在安裝最新的插件之后,有可能會產(chǎn)生沒有樣式標(biāo)識和樣式提示的問題,這里需要在settings.json(這里是針對vscode的問題) 文件中添加一個屬性
//settings.json
{
//其他配置
//...
//假如你的項目在D:/git-item/my-item/你所保存的所有項目,那么這里的屬性值就可以是D:/git-item/my-item(或者加上你的詳細(xì)項目)
"unocss.root": "你當(dāng)前項目的絕對路徑",
}
原子化樣式目前來說是一種CSS的發(fā)展趨勢,可以使用。也可以選擇不用,畢竟現(xiàn)在的CSS已經(jīng)發(fā)展很成熟了,包括Sass、Less等一些預(yù)編譯器也發(fā)展的很成熟,他們都有自己變量函數(shù)等一些操作,如果想要寫一個主題,使用變量來實現(xiàn)是一個很好選擇。
當(dāng)然,最后個人覺得原子化樣式在Vue、Servlet等這種對CSS的處理很好的框架中不是很好的選擇。如果是React等這種對CSS處理沒有那么好的框架中,除了CSS-in-JS還是很不錯的選擇
原文鏈接:https://juejin.cn/post/7322401091237068854
動態(tài)的 web 應(yīng)用同樣需要靜態(tài)文件。CSS 和 JavaScript 文件通常來源于此。理想情況下,你的 web 服務(wù)器已經(jīng)配置好為它們服務(wù),然而在開發(fā)過程中 Flask 就能夠做到。只要在你的包中或模塊旁邊創(chuàng)建一個名為static 的文件夾,在應(yīng)用中使用 /static 即可訪問。
給靜態(tài)文件生成 URL ,使用特殊的 static 端點名:
url_for('static', filename='style.css')
這個文件是應(yīng)該存儲在文件系統(tǒng)上的static/style.css。
在 Python 中生成 HTML 并不好玩,實際上是相當(dāng)繁瑣的,因為你必須自行做好 HTML 轉(zhuǎn)義以保持應(yīng)用程序的安全。由于這個原因,F(xiàn)lask 自動為你配置好 Jinja2 模板。
你可以使用方法 render_template() 來渲染模板。所有你需要做的就是提供模板的名稱以及你想要作為關(guān)鍵字參數(shù)傳入模板的變量。
這里有個渲染模板的簡單例子,在 /home/mysite/Code 目錄下新建 hello.py 文件,并向其中添加如下代碼:
Flask 將會在 templates 文件夾中尋找模板。因此如果你的應(yīng)用是個模塊,這個文件夾在模塊的旁邊,如果它是一個包,那么這個文件夾在你的包里面:
比如,應(yīng)用是模塊:
比如,應(yīng)用是包:
/application /__init__.py /templates /hello.html
對于模板,你可以使用 Jinja2 模板的全部能力。詳細(xì)信息查看官方的 Jinja2 Template Documentation 。
在 /home/mysite/Code 目錄下新建 templates 文件夾并在其中新建 hello.html 文件:
照前面的方法運(yùn)行應(yīng)用程序,當(dāng)訪問 http://127.0.0.1:5000/hello/ 時頁面顯示 Hello World!;當(dāng)訪問 http://127.0.0.1:5000/hello/shiyanlou 時頁面顯示 Hello shiyanlou!。
在模板中你也可以使用request,session和g對象,也能使用函數(shù)get_flashed_messages() 。
模板繼承是十分有用的。如果想要知道模板繼承如何工作的話,請閱讀文檔模板繼承。基本的模板繼承使得某些特定元素(如標(biāo)題、導(dǎo)航和頁腳)在每一頁成為可能。
自動轉(zhuǎn)義默認(rèn)是開啟的,因此如name包含 HTML,它將會自動轉(zhuǎn)義。如果你信任一個變量,并且你知道它是安全的(例如一個模塊把 wiki 標(biāo)記轉(zhuǎn)換到 HTML ),你可以用Markup類或|safe過濾器在模板中標(biāo)記它是安全的。 在 Jinja 2 文檔中,你會見到更多例子。
下面有一個Markup類如何工作的基本介紹,在 Python3 交互式命令行中執(zhí)行如下命令:
*請認(rèn)真填寫需求信息,我們會在24小時內(nèi)與您取得聯(lián)系。