django模板语法-对整数取余运算

2019年3月6日 15:58 by wst

django

起因

在往模板填充数据的时候,本来是个从数据库里查出来的列表,每一项在显示的时候,根据不同的下标显示不同的样式。

比如第一个显示红色,第二个显示蓝色,第三个显示黄色。第四个又显示红色,第五个显示蓝色。。。

 

很容想到的就是对3取余,值为1则为红色;值为2显示蓝色;值为3显示黄色。

奈何模板的过滤器里没有这个用法,尝试过divisibleby,也没解决此问题。

还好可以自定义过滤器。

解决方法

这里给出核心代码:

1. 自定义过滤器mod.py(顺便给出了自定义标签的用法)

from django import template

register = template.Library()   #register的名字是固定的,不可改变

####################以上行是固定不变要写的#############################


######################定义过滤器####################
@register.filter
def filter_mod(v1,v2):
    return  v1%v2

######################定义标签#####################
@register.simple_tag
def simple_tag_multi(v1,v2):
    return  v1 * v2

2. 模板文件index.html

<html>
    <head>
        <title>test</title>
    <style>
        .class1 {
            color: red;
        }
        .class2 {
            color:blue;
        }
        .class3 {
            color:yellow;
        }
    </style>
    </head>
    <body>
        <h1>模板语法整数取余运算</h1>
        {% load mod %}
        {% for x in obj %}
        {% if forloop.counter|filter_mod:3 == 1 %}
        <p class="class1">good{{x}}</p>
        {% elif forloop.counter|filter_mod:3 == 2 %}
        <p class="class2">good{{x}}</p>
        {% else %}
        <p class="class3">good{{x}}</p>
        {% endif %}
        {% endfor %}
    </body>
</html>

3. 视图文件views.py

from django.shortcuts import render

def index(request):
    return render(request, "index.html", {"obj":[1,2,3,4]})

 

4. 完整的目录结构如下:

.
├── db.sqlite3
├── divd
│   ├── __init__.py
│   ├── settings.py
│   ├── templates
│   │   └── index.html
│   ├── templatetags
│   │   ├── __init__.py
│   │   └── mod.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
└── manage.py

 

如果想要完整的可运行的所有代码,请关注下方公众号并回复“django模板取余”


Comments(127) Add Your Comment

Charlesnag
“I haven’t seen you in these parts,” the barkeep said, sidling settled to where I sat. “Personage’s Bao.” He stated it exuberantly, as if say of his exploits were shared by way of settlers about many a ‚lan in Aeternum. He waved to a unimpassioned butt apart from us, and I returned his gesture with a nod. He filled a telescope and slid it to me across the stained red wood of the bench prior to continuing. “As a betting houseman, I’d be delighted to wager a honourable speck of coin you’re in Ebonscale Reach on the side of more than the wet one's whistle and sights,” he said, eyes glancing from the sword sheathed on my hip to the capitulate slung across my back. http://maps.google.gr/url?q=https://renewworld.ru/sistemnye-trebovaniya-new-world/
Jmhnwg
lipitor 10mg tablet <a href="https://lipiws.top/">buy atorvastatin 40mg generic</a> atorvastatin 20mg usa
Xnyneq
order cipro 1000mg pills - <a href="https://metroagyl.top/keflexcapsule/">purchase cephalexin generic</a> buy augmentin 625mg generic
Hjsixu
cheap cipro 500mg - <a href="https://cipropro.top/keflexcapsule/">cephalexin 125mg sale</a> buy augmentin 1000mg for sale
Aclxeb
buy flagyl - <a href="https://metroagyl.top/azithromycin/">azithromycin where to buy</a> where can i buy zithromax
Svcqcj
ciprofloxacin 500mg drug - <a href="https://septrim.top/erythromycin/">order erythromycin 250mg</a> erythromycin 500mg brand
Dodnib
order valtrex online - <a href="https://gnantiviralp.com/">buy valtrex online cheap</a> buy acyclovir 800mg generic
Qhmcja
stromectol order online - <a href="https://keflexin.top/cefixime/">order suprax sale</a> order tetracycline 500mg generic
Syhrvx
metronidazole pills - <a href="https://metroagyl.top/clindamycin/">cleocin 300mg canada</a> buy generic azithromycin online
Nxiyez
brand acillin <a href="https://ampiacil.top/amoxil500/">purchase amoxil pill</a> amoxicillin oral
Cxjwpr
lasix cost - <a href="https://antipathogenc.com/medex/">buy coumadin for sale</a> captopril 25mg price
Vvwpnb
generic retrovir 300mg - <a href="https://canadiangnp.com/allopurinol/">buy allopurinol paypal</a> allopurinol 300mg price
Ozywck
order glycomet 500mg online cheap - <a href="https://gnantiacidity.com/combivir/">lamivudine order</a> order lincocin generic
Typthf
generic clozapine - <a href="https://genonlinep.com/accupril/">cheap quinapril 10mg</a> pepcid 20mg cheap
Dzpuqs
buy seroquel generic - <a href="https://gnkantdepres.com/bupron/">cheap bupron SR without prescription</a> buy eskalith tablets
Dcnmhj
hydroxyzine 25mg uk - <a href="https://antdepls.com/">atarax 25mg sale</a> buy cheap endep
Sgkvve
anafranil usa - <a href="https://antdeponline.com/cymbalta/">cymbalta medication</a> buy doxepin 75mg online cheap
Xtwozy
cheap amoxil sale - <a href="https://atbioxotc.com/cefadroxil/">duricef 250mg for sale</a> buy cipro online cheap
Mqbzbz
order augmentin online - <a href="https://atbioinfo.com/septra/">order bactrim 960mg without prescription</a> oral cipro 1000mg
Qmplzi
buy generic clindamycin over the counter - <a href="https://cadbiot.com/chloramphenicol/">buy chloramphenicol tablets</a> buy chloromycetin generic
Svmkuq
buy zithromax without prescription - <a href="https://gncatbp.com/btetracycline/">tetracycline uk</a> order ciprofloxacin generic
Tqjhvc
how to get ventolin without a prescription - <a href="https://antxallergic.com/">buy ventolin 2mg inhaler</a> how to get theo-24 Cr without a prescription
Fijnuv
ivermectin drug - <a href="https://antibpl.com/aqdapsone/">aczone ca</a> cost cefaclor 500mg
Tcyorq
purchase clarinex generic - <a href="https://rxtallerg.com/beclomethasone/">order beclamethasone nasal spray</a> albuterol 2mg cheap
Myyxnv
buy medrol without prescription - <a href="https://ntallegpl.com/getcetirizine/">zyrtec cost</a> buy azelastine without a prescription
Okpqjk
buy micronase 2.5mg - <a href="https://prodeprpl.com/">order micronase online cheap</a> buy dapagliflozin 10mg generic
Rmcfks
purchase repaglinide online cheap - <a href="https://depressinfo.com/">buy prandin cheap</a> empagliflozin drug
Emhfda
buy glucophage 500mg generic - <a href="https://arxdepress.com/losartan25/">buy cozaar no prescription</a> pill acarbose
Znivwe
lamisil 250mg brand - <a href="https://treatfungusx.com/adiflucanv/">order fluconazole 100mg online cheap</a> purchase grifulvin v generic
Eqwkro
rybelsus 14mg drug - <a href="https://infodeppl.com/ddavpspray/">buy generic desmopressin over the counter</a> DDAVP usa
Vladns
buy nizoral 200 mg online cheap - <a href="https://antifungusrp.com/clotrithasone/">order lotrisone without prescription</a> itraconazole 100 mg cheap
Hnrxkw
buy lanoxin for sale - <a href="https://blpressureok.com/avalidemed/">buy cheap avapro</a> buy lasix 100mg sale
Bzfasg
famciclovir 500mg cost - <a href="https://amvinherpes.com/acyclovircream/">buy generic zovirax over the counter</a> order valcivir generic
Frsqrp
brand microzide 25 mg - <a href="https://norvapril.com/amlodipine/">amlodipine 10mg sale</a> buy bisoprolol generic
Deewol
metoprolol where to buy - <a href="https://bloodpresspl.com/telmisartan/">telmisartan oral</a> adalat price
Ogaefp
buy generic nitroglycerin online - <a href="https://nitroproxl.com/clonidinechlorthalidone/">combipres order online</a> order diovan 80mg generic
Umonjn
crestor pills bark - <a href="https://antcholesterol.com/pravastatin/">pravastatin online menace</a> caduet pills glass
Pipgnp
simvastatin rain - <a href="https://canescholest.com/fenofibrate/">fenofibrate hopeful</a> order atorvastatin 20mg pills
Ilnlsk
viagra professional learn - <a href="https://edsildps.com/viagragold/">viagra gold definite</a> levitra oral jelly online brandy
Fsjqka
dapoxetine halt - <a href="https://promedprili.com/sildigra/">sildigra advise</a> cialis with dapoxetine improve
Ctiato
cenforce online purpose - <a href="https://xcenforcem.com/silagrasildenafil/"></a> brand viagra across
Pvaocm
brand cialis buck - <a href="https://probrandtad.com/alprostadilonline/">alprostadil fellow</a> penisole roof
Khtbkd
cialis soft tabs online concern - <a href="https://supervalip.com/">cialis soft tabs pills south</a> viagra oral jelly online fragment
Ngqhsr
brand cialis indeed - <a href="https://probrandtad.com/tadorapills/">tadora artist</a> penisole university
Uexbts
cialis soft tabs pills never - <a href="https://supervalip.com/viagraoraljelly/">viagra oral jelly ashamed</a> viagra oral jelly admire
Mipbvd
cenforce stir - <a href="https://xcenforcem.com/brandviagrasildenafil/">brand viagra online expedition</a> brand viagra pills render
Xaodhq
acne treatment theory - <a href="https://placnemedx.com/">acne medication unexpected</a> acne medication foolish
Hcuwtz
asthma treatment content - <a href="https://bsasthmaps.com/">inhalers for asthma bad</a> asthma medication lad
Yvecpe
uti antibiotics percy - <a href="https://amenahealthp.com/">treatment for uti letter</a> uti medication corridor
Rvigqa
prostatitis treatment permission - <a href="https://xprosttreat.com/">prostatitis treatment climb</a> prostatitis medications medical
Xhodkf
valtrex pills fourth - <a href="https://gnantiviralp.com/">valacyclovir pills minister</a> valtrex pills irish
Mihwyp
loratadine medication thou - <a href="https://clatadine.top/">loratadine main</a> loratadine medication stern
Vsasvi
claritin weird - <a href="https://clatadine.top/">claritin personality</a> loratadine surround
Rshhry
priligy represent - <a href="https://prilixgn.top/">priligy pocket</a> priligy color
Qqqhjm
promethazine museum - <a href="https://prohnrg.com/">promethazine write</a> promethazine twilight
Cnfege
ascorbic acid life - <a href="https://ascxacid.com/">ascorbic acid mister</a> ascorbic acid lodge
Jeicgj
florinef pills stranger - <a href="https://gastroplusp.com/">florinef bear</a> prevacid resume
Psdfkg
biaxin true - <a href="https://gastropls.com/ranitidineonline/">zantac pills reality</a> cytotec pills scent
Yhgdmw
dulcolax over the counter - <a href="https://gastroinfop.com/liv52/">cheap liv52 10mg</a> liv52 for sale online
Geifie
buy generic rabeprazole - <a href="https://gastrointesl.com/metoclopramide/">purchase metoclopramide generic</a> domperidone price
Llugft
where can i buy cotrimoxazole - <a href="https://ketiracet.com/">buy keppra no prescription</a> buy tobra no prescription
Cityun
buy generic eukroma for sale - <a href="https://dupsteron.com/">cost duphaston</a> dydrogesterone generic
Bupull
purchase forxiga sale - <a href="https://forpaglif.com/">order forxiga 10 mg generic</a> acarbose 25mg generic
Pwhwvl
order fulvicin generic - <a href="https://fulviseoful.com/">order generic griseofulvin</a> pill lopid 300 mg
Alvsge
buy vasotec 5mg generic - <a href="https://xalanoprost.com/">xalatan uk</a> buy xalatan
Wnolet
dramamine generic - <a href="https://bisacolax.com/">buy dimenhydrinate cheap</a> risedronate 35 mg pill
Ifnlip
feldene 20 mg cheap - <a href="https://rivastilons.com/">rivastigmine 3mg cheap</a> cheap rivastigmine
Neurjr
buy monograph 600mg sale - <a href="https://cilosetal.com/">order pletal generic</a> order pletal 100 mg
Roevqt
buy hydroxyurea pills for sale - <a href="https://hydroydrinfo.com/methocarbamol/">order robaxin pill</a> methocarbamol over the counter
Dgdacc
buy piracetam without a prescription - <a href="https://nootquin.com/secnidazole/">secnidazole online</a> buy sinemet pills for sale
Whjrkf
disopyramide phosphate online - <a href="https://anorpica.com/">buy norpace</a> chlorpromazine online buy
Ipyiru
buy generic depakote for sale - <a href="https://adepamox.com/mefloquine/">order lariam generic</a> buy topamax 100mg without prescription
Larabz
cyclophosphamide order online - <a href="https://cycloxalp.com/dimenhydrinate/">order dimenhydrinate</a> purchase vastarel online
Jkvsfw
aldactone buy online - <a href="https://aldantinep.com/carbamazepine/">cheap carbamazepine without prescription</a> revia sale
Zfrbfy
flexeril 15mg without prescription - <a href="https://abflequine.com/">cyclobenzaprine for sale</a> pill enalapril 10mg
Ckopte
zofran oral - <a href="https://azofarininfo.com/selegiline/">order selegiline for sale</a> requip 2mg us
Accltn
buy ascorbic acid generic - <a href="https://mdacidinfo.com/lopinavirritonavir/">cheap lopinavir ritonavir generic</a> order compro for sale
Xgtfkn
durex gel online order - <a href="https://xalaplinfo.com/latanoprosteyedrops/">purchase zovirax without prescription</a> zovirax order
Ghlrjs
arava 10mg without prescription - <a href="https://infohealthybones.com/">buy arava 10mg without prescription</a> order cartidin generic
Aipdeq
rogaine online buy - <a href="https://hairlossmedinfo.com/finasteridefinp/">order finpecia</a> order finasteride 5mg generic
Rmxqzb
brand tenormin 50mg - <a href="https://heartmedinfox.com/clopidogrel/">buy generic clopidogrel over the counter</a> coreg generic
Uhuqxr
buy verapamil generic - <a href="https://infoheartdisea.com/cardizem/">diltiazem 180mg cost</a> purchase tenoretic online
Eunsrm
cheap atorvastatin tablets - <a href="https://infoxheartmed.com/enalapril/">purchase vasotec for sale</a> buy bystolic pills for sale
Hsyeqa
purchase lasuna - <a href="https://infoherbalmz.com/himcolin/">himcolin drug</a> himcolin canada
Oemsji
cheap speman tablets - <a href="https://spmensht.com/">speman cost</a> order finasteride pill
Apbwgd
noroxin oral - <a href="https://gmenshth.com/confido/">purchase confido</a> confido pills
Cbllsz
finasteride canada - <a href="https://finmenura.com/">finasteride over the counter</a> uroxatral order online
Jinafj
hytrin price - <a href="https://hymenmax.com/dapoxetine/">order dapoxetine without prescription</a> buy priligy 30mg pill
Nocgad
lactulose order online - <a href="https://duphalinfo.com/mentat/">buy brahmi no prescription</a> cheap betahistine 16 mg
Qejxkl
buy trileptal 600mg online - <a href="https://trileoxine.com/pirfenidone/">pirfenidone brand</a> levoxyl pills
Srrcom
order generic imusporin - <a href="https://asimusxate.com/">order imusporin eye drops</a> buy colchicine pills
Fmpnaa
buy calcort online - <a href="https://lazacort.com/brimonidine/">alphagan medication</a> buy alphagan eye drops
Hhufor
besivance without prescription - <a href="https://besifxcist.com/sildamax/">sildamax brand</a> cheap sildamax
Ectvtr
buy neurontin 100mg for sale - <a href="https://aneutrin.com/ibuprofen/">nurofen usa</a> azulfidine 500mg cheap
Ahnapy
how to get probenecid without a prescription - <a href="https://bendoltol.com/monograph/">order etodolac online</a> order generic tegretol 200mg
Dqydio
celecoxib tablet - <a href="https://celespas.com/indomethacin/">indomethacin tablet</a> order indocin 50mg
Xkekzy
colospa order - <a href="https://coloxia.com/pletal/">how to buy pletal</a> order pletal 100mg generic
Wxwpto
purchase voltaren generic - <a href="https://dicloltarin.com/">purchase cambia sale</a> aspirin where to buy
Ifpyqz
purchase rumalaya generic - <a href="https://rumaxtol.com/">buy rumalaya generic</a> elavil 10mg canada
Etlxye
buy pyridostigmine 60 mg sale - <a href="https://mestonsx.com/asumatriptan/">sumatriptan generic</a> order imuran 25mg
Wawypl
baclofen oral - <a href="https://baclion.com/nspiroxicam/">piroxicam 20 mg usa</a> purchase piroxicam without prescription
Jmbgvv
buy diclofenac tablets - <a href="https://vovetosa.com/tisosorbide/">imdur usa</a> cheap nimotop for sale
Ydsudj
cyproheptadine price - <a href="https://periheptadn.com/aszanaflex/">zanaflex drug</a> tizanidine 2mg for sale
Pnnxza
buy meloxicam 15mg pills - <a href="https://meloxiptan.com/asrizatriptan/">maxalt 10mg sale</a> toradol 10mg sale
Jvhrmj
order generic omnicef 300 mg - <a href="https://omnixcin.com/">cost omnicef</a> cleocin gel
Xbydxm
artane oral - <a href="https://voltapll.com.com/">buy cheap generic artane</a> where can i buy emulgel
Gzgcqb
order accutane pill - <a href="https://aisotane.com/">order accutane 10mg</a> deltasone 5mg uk
Cmdmmt
buy prednisone 40mg pill - <a href="https://apreplson.com/permethrin/">cost zovirax</a> elimite over the counter
Kfdous
permethrin usa - <a href="https://actizacs.com/tretinoin/">tretinoin gel oral</a> retin gel generic
Uslfrx
betamethasone 20 gm cheap - <a href="https://betnoson.com/awdifferin/">purchase adapalene without prescription</a> monobenzone online buy
Hesurt
buy generic metronidazole for sale - <a href="https://ametronles.com/">flagyl brand</a> cenforce 100mg us
Kcvgfq
order augmentin 625mg - <a href="https://baugipro.com/">cheap clavulanate</a> cheap levoxyl
Xnicro
order hyzaar online cheap - <a href="https://acephacrsa.com/">purchase keflex online</a> cephalexin 500mg uk
Qlhfia
buy clindamycin without prescription - <a href="https://clinycinpl.com/">cleocin oral</a> buy cheap generic indocin
Qkhfgi
buy eurax no prescription - <a href="https://aeuracream.com/">crotamiton for sale online</a> order aczone for sale
Vcptkg
provigil online - <a href="https://sleepagil.com/melatonin/">buy meloset 3mg sale</a> order melatonin 3mg generic
Ghmfgl
buy bupropion 150 mg online - <a href="https://bupropsl.com/">purchase zyban without prescription</a> buy shuddha guggulu pills
Geqhbs
xeloda over the counter - <a href="https://xelocap.com/">order xeloda 500 mg generic</a> danazol order
Rhsnmv
purchase progesterone generic - <a href="https://apromid.com/clomiphene/">serophene over the counter</a> fertomid pills
Sgxwvw
order alendronate 35mg online - <a href="https://pilaxmax.com/medroxyprogesterone/">buy provera pills for sale</a> cheap medroxyprogesterone 10mg
Ztceqi
order norethindrone 5mg generic - <a href="https://norethgep.com/bimatoprost/">cost careprost</a> purchase yasmin
Bwixen
cost estrace - <a href="https://festrolp.com/">order estrace 1mg online cheap</a> anastrozole 1mg brand
Dtsqys
cabergoline 0.5mg cheap - <a href="https://adostilin.com/alesse/">alesse usa</a> buy alesse generic
Seilpi
プレドニンの購入 - <a href="https://jpaonlinep.com/">プレドニン通販おすすめ</a> アジスロマイシン 薬局で買える
Rrkbix
г‚·гѓ«гѓ‡гѓЉгѓ•г‚Јгѓ« е‰ЇдЅњз”Ё - <a href="https://jpedpharm.com/tadalafil/">г‚їгѓЂгѓ©гѓ•г‚Јгѓ« гЃЉгЃ™гЃ™г‚Ѓ</a> г‚·г‚ўгѓЄг‚№ еЂ¤ж®µ
Njhtmz
プレドニン処方 - <a href="https://jpanfarap.com/">プレドニン通販おすすめ</a> アキュテイン錠 5 mg 強さ
Wvsfyj
eriacta crouch - <a href="https://eriagra.com/szenegrag/">zenegra carriage</a> forzest sound