我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.templatetags.static.static()。
def martiallaw(result, timediff=None): from wawmembers.utilities import timedeltadivide imgloc = static('wawmembers/martiallaw.gif') if timediff != None: h, m, s = timedeltadivide(timediff) if result == 'NotAtWar': message = "You can only declare a global state of martial law in wartime." elif result == 'Dictator': message = "You refuse to give up your ultimate power to the Fleet Admiralty!" elif result == 'AlreadyAdmiralty': message = "The Fleet Admiralty is already in control of your world!" elif result == 'TooSoon': message = "You can only declare martial law once every 4 turns! You still have %s:%s:%s before you can re-declare." % (h, m, s) elif result == 'UnderTime': message = "None of your wars have been long enough to warrant declaring Martial Law! You still have %s:%s:%s \ before you can enact this policy." % (h, m, s) elif result == 'Success': message = """<img src="%s" alt="arrest"><br>The Fleet Admiralty seizes control of your world as martial law<br> \ is declared. You gain some of your best ships!""" % imgloc return message
def newbevent(name): #type 2 imgloc = static('actionnews/newworld.gif') data = """<center> \ Welcome to the Galaxy, %s! Choose the path your world has taken carefully. \ <p class="halfline"> </p> \ <img src="%s" alt="newworld"> \ <p class="halfline"> </p> \ <table> \ <tr> \ <td class='center'><input type='submit' name='noobmoney' value='Economy' class='button' \ title='You have 600 GEU for you to spend however you see fit.'/></td> \ <td class='center'><input type='submit' name='noobqol' value='Welfare' class='button' \ title='Your people love you and have higher quality of life.'/></td> \ <td class='center'><input type='submit' name='noobsecurity' value='Security' class='button' \ title='Your rule is extremely solid.'/></td> \ <td class='center'><input type='submit' name='noobmilitary' value='Military' class='button' \ title='You have a strong military.'/></td> \ </tr> \ </table> \ </center>""" % (name, imgloc) return data
def asteroidevent(): #type 4 imgloc = static('actionnews/asteroidmine.gif') data = """<center> \ You track an asteroid entering your system to find it is saturated with resources. <br> \ However, due to its small size you may only build one mine on it. What do you choose? \ <p class="halfline"> </p> \ <img src="%s" alt="asteroidmine"> \ <p class="halfline"> </p> \ <table> \ <tr> \ <td class='center'><input type='submit' name='asteroidduranium' value='Duranium' class='button' \ title='You will gain one duranium mine.'/></td> \ <td class='center'><input type='submit' name='asteroidtritanium' value='Tritanium' class='button' \ title='You will gain one tritanium mine.'/></td> \ <td class='center'><input type='submit' name='asteroidadamantium' value='Adamantium' class='button' \ title='You will gain one adamantium mine.'/></td> \ </tr> \ </table> \ </center>""" % imgloc return data
def dangerasteroid(): #type 5 imgloc = static('actionnews/dangerasteroid.gif') data = """<center> \ Your fleet intelligence detects an asteroid on a collision course <br> \ directly for the planet! What should be done? \ <p class="halfline"> </p> \ <img src="%s" alt="dangerasteroid"> \ <p class="halfline"> </p> \ <table> \ <tr> \ <td class='center'><input type='submit' name='dasteroiddeflect' value='Deflect' class='button' \ title='Get your support ships to deflect it harmlessly into space, at the cost of 50 warpfuel.'/></td> \ <td class='center'><input type='submit' name='dasteroidsubcontract' value='Subcontract' class='button' \ title='Pay a civilian company to deflect it for you, at the cost of 500 GEU.'/></td> \ <td class='center'><input type='submit' name='dasteroidredirect' value='Redirect' class='button' \ title='Redirect it onto a rebel area on your planet at the cost of 20 warpfuel. \ Rebels will be heavily reduced but you will lose perception.'/></td> \ </tr> \ </table> \ </center>""" % imgloc return data
def rebeladmiral(): #type 6 imgloc = static('actionnews/rebeladmiral.gif') data = """<center> \ One of your admirals is gathering popularity with the people. You have even <br> \ heard rumours that he might dare to rise against you! What should be done?\ <p class="halfline"> </p> \ <img src="%s" alt="rebeladmiral"> \ <p class="halfline"> </p> \ <table> \ <tr> \ <td class='center'><input type='submit' name='radmiralignore' value='Ignore' class='button' \ title='Your people love you, they would never rebel. Ignore this annoyance.'/></td> \ <td class='center'><input type='submit' name='radmiralbribe' value='Bribe' class='button' \ title='Pay 250 GEU to convince the admiral to retire with a comfortable pension.'/></td> \ <td class='center'><input type='submit' name='radmiralspy' value='Assassinate' class='button' \ title='Send a spy to cause the admiral to have an \'unfortunate accident\'.'/></td> \ </tr> \ </table> \ </center>""" % imgloc return data
def traderaiders(): #type 7 imgloc = static('actionnews/traderaiders.gif') data = """<center> \ Raiders have been harassing your trade ships. What should be done? \ <p class="halfline"> </p> \ <img src="%s" alt="traderaiders"> \ <p class="halfline"> </p> \ <table> \ <tr> \ <td class='center'><input type='submit' name='traidersattack' value='Attack' class='button' \ title='This cannot stand! Send your home fleet to crush these rats.'/></td> \ <td class='center'><input type='submit' name='traidersbribe' value='Bribe' class='button' \ title='Pay 500 GEU to try and make them go away.'/></td> \ <td class='center'><input type='submit' name='traidersignore' value='Ignore' class='button' \ title='We have far more important things to worry about than a couple of petty raiders.'/></td> \ </tr> \ </table> \ </center>""" % imgloc return data
def durasteroid(): #type 8 imgloc = static('actionnews/durasteroid.gif') data = """<center> \ An asteroid impacts on your world, with minor casualties. Quality of <br> \ life drops slightly, but you discover the asteroid is full of duranium! \ <p class="halfline"> </p> \ <img src="%s" alt="durasteroid"> \ <p class="halfline"> </p> \ <table> \ <tr> \ <td class='center'><input type='submit' name='durasteroidmine' value='Mine' class='button' \ title='Extract as much as you can.'/></td> \ </tr> \ </table> \ </center>""" % imgloc return data
def xenu(): #type 10 imgloc = static('actionnews/xenu.gif') data = """<center> \ A galactic despot arrives in orbit in what looks like a DC-8 airplane from <br>\ old Earth. He asks if he can dump off some spare spirits on your world. <p class="halfline"> </p> \ <img src="%s" alt="xenu"> \ <p class="halfline"> </p> \ <table> \ <tr> \ <td class='center'><input type='submit' name='xenuaccept' value='Accept' class='button' \ title='Yeah, why not? Could be a laff.'/></td> \ <td class='center'><input type='submit' name='xenurefuse' value='Refuse' class='button' \ title='lol r u crazy m8 gtfo b4 u get hooked in da gabber'/></td> \ </tr> \ </table> \ </center>""" % imgloc return data
def bgchoice(context): background = GlobalData.objects.get(pk=1).turnbackground request = context['request'] try: world = World.objects.get(user=request.user) except: return static('backgrounds/%s.gif' % background) else: if world.backgroundpref == -1: return static('backgrounds/%s.gif' % v.background()) elif world.backgroundpref == -2: return static('backgrounds/%s.gif' % background) else: return static('backgrounds/%s.gif' % world.backgroundpref)
def compatible_staticpath(path): ''' Try to return a path to static the static files compatible all the way back to Django 1.2. If anyone has a cleaner or better way to do this let me know! ''' try: # >= 1.4 from django.templatetags.static import static return static(path) except ImportError: pass try: # >= 1.3 return '%s/%s' % (settings.STATIC_URL.rstrip('/'), path) except AttributeError: pass try: return '%s/%s' % (settings.PAGEDOWN_URL.rstrip('/'), path) except AttributeError: pass return '%s/%s' % (settings.MEDIA_URL.rstrip('/'), path)
def serialize_file(instance, file_attr='file', thumbnail_attr='artwork'): obj = getattr(instance, file_attr) thumbnail = getattr(instance, thumbnail_attr) if thumbnail: thumbnail_url = thumbnail.url else: thumbnail_url = static('box/images/NoArtwork_Black.png') return { 'url': obj.url, 'name': order_name(obj.name), 'type': mimetypes.guess_type(obj.path)[0], 'thumbnailUrl': thumbnail_url, 'size': obj.size, 'deleteUrl': reverse('box:song-delete', kwargs={'username': instance.user.username, 'slug': instance.slug}), 'deleteType': 'DELETE', }
def static(path): global _static if _static is None: if apps.is_installed('django.contrib.staticfiles'): from django.contrib.staticfiles.templatetags.staticfiles import static as _static else: from django.templatetags.static import static as _static return _static(path)
def absolute_path(self, path): """ Given a relative or absolute path to a static asset, return an absolute path. An absolute path will be returned unchanged while a relative path will be passed to django.templatetags.static.static(). """ if path.startswith(('http://', 'https://', '/')): return path return static(path)
def static(path): # Backwards compatibility alias for django.templatetags.static.static(). # Deprecation should start in Django 2.0. return _static(path)
def _boolean_icon(field_val): icon_url = static('admin/img/icon-%s.svg' % {True: 'yes', False: 'no', None: 'unknown'}[field_val]) return format_html('<img src="{}" alt="{}" />', icon_url, field_val)
def xstatic(*tags): from .vendors import vendors node = vendors fs = [] lang = get_language() cls_str = str if six.PY3 else basestring for tag in tags: try: for p in tag.split('.'): node = node[p] except Exception as e: if tag.startswith('xadmin'): file_type = tag.split('.')[-1] if file_type in ('css', 'js'): node = "xadmin/%s/%s" % (file_type, tag) else: raise e else: raise e if isinstance(node, cls_str): files = node else: mode = 'dev' if not settings.DEBUG: mode = getattr(settings, 'STATIC_USE_CDN', False) and 'cdn' or 'production' if mode == 'cdn' and mode not in node: mode = 'production' if mode == 'production' and mode not in node: mode = 'dev' files = node[mode] files = type(files) in (list, tuple) and files or [files, ] fs.extend([f % {'lang': lang.replace('_', '-')} for f in files]) return [f.startswith('http://') and f or static(f) for f in fs]
def xstatic(*tags): from vendors import vendors node = vendors fs = [] lang = get_language() for tag in tags: try: for p in tag.split('.'): node = node[p] except Exception, e: if tag.startswith('xadmin'): file_type = tag.split('.')[-1] if file_type in ('css', 'js'): node = "xadmin/%s/%s" % (file_type, tag) else: raise e else: raise e if type(node) in (str, unicode): files = node else: mode = 'dev' if not settings.DEBUG: mode = getattr(settings, 'STATIC_USE_CDN', False) and 'cdn' or 'production' if mode == 'cdn' and mode not in node: mode = 'production' if mode == 'production' and mode not in node: mode = 'dev' files = node[mode] files = type(files) in (list, tuple) and files or [files, ] fs.extend([f % {'lang': lang.replace('_', '-')} for f in files]) return [f.startswith('http://') and f or static(f) for f in fs]
def get_photo_url(self): if self.photo: return self.photo.url else: return static('img/gift.jpg')
def post_valid(self, request): """Expects a POST request from Twilio, and return a response directing Twilio to play the greeting mp3 and post the recorded response to the handle voicemail URL """ response = VoiceResponse() self.static_greeting_path = static(self.voicemail_static_path) self.record_voicemail_url = request.build_absolute_uri( reverse('phone-handle_new_message')).replace('http:', 'https:') response.play(self.static_greeting_path) response.record(action=self.record_voicemail_url, method='POST') return HttpResponse(response)
def normal_avatar(self): if self.avatar: return self.avatar.normal.url_nocache else: return static('users/img/default_150x150.png')
def small_avatar(self): if self.avatar: return self.avatar.small.url_nocache else: return static('users/img/default_50x50.png')
def micro_avatar(self): if self.avatar: return self.avatar.micro.url_nocache else: return static('users/img/default_32x32.png')
def regenerate_css(event_id: int): event = Event.objects.get(pk=event_id) local_apps = ['agenda', 'cfp', 'orga'] if not event.primary_color: for local_app in local_apps: event.settings.delete(f'{local_app}_css_file') event.settings.delete(f'{local_app}_css_checksum') return for local_app in local_apps: path = os.path.join(settings.STATIC_ROOT, local_app, 'scss/main.scss') sassrules = [] if event.primary_color: sassrules.append('$brand-primary: {};'.format(event.primary_color)) sassrules.append(f'@import "{path}";') cf = dict(django_libsass.CUSTOM_FUNCTIONS) cf['static'] = static css = sass.compile( string="\n".join(sassrules), output_style='compressed', custom_functions=cf ) checksum = hashlib.sha1(css.encode('utf-8')).hexdigest() fname = f'{event.slug}/{local_app}.{checksum[:16]}.css' if event.settings.get(f'{local_app}_css_checksum', '') != checksum: newname = default_storage.save(fname, ContentFile(css.encode('utf-8'))) event.settings.set(f'{local_app}_css_file', f'/media/{newname}') event.settings.set(f'{local_app}_css_checksum', checksum)
def noobgrowth(result): imgloc = static('wawmembers/cheap.gif') if result == 'TooRich': message = "Your world is too rich for cheap goods to have an effect on growth!" elif result == 'Success': message = """<img src="%s" alt="cheap"><br>Your world gains some growth off the back of cheap stuff.""" % imgloc return message
def buybonds(result): imgloc = static('wawmembers/buybonds.gif') if 50 < result <= 100: message = """<img src="%s" alt="buybonds"><br>Growth increases as your buying program drives up the supply of money.""" % imgloc elif 1 <= result <= 50: message = "Despite your buying program, the economy fails to grow." elif result == 'NotFreeorMixed': message = "You are a Central Planning world!" return message
def forcedlabour(result): imgloc = static('wawmembers/forcedlabour.gif') if 15 < result <= 100: message = """<img src="%s" alt="forcedlabour"><br>Growth increases as your dissenters are put to back-breaking work.""" % imgloc elif 10 < result <= 15: message = "Despite your harsh work hours, your dissenters do not manage to increase global growth." elif 1 <= result <= 10: message = "The dissenters escape and join the rebels!" elif result == 'NotDictatorship': message = "Only autocracies have enough dissenters to put to work!" elif result == 'StabilityTooLow': message = "Your stability is too low! You cannot risk a collapse of your rule!" return message
def buildfuelrefinery(result): imgloc = static('wawmembers/warpfuel.gif') if result == 'TooMany': message = "Your fleet engineers cannot build so many fuel refineries in one day!" elif result == 'Failure': message = "Unfortunately your refinery suffered a catastrophic failure when setting up." elif result == 'Success': message = """<img src="%s" alt="production"><br>Your refinery set up successfully! \ <br>You gain 10 warpfuel per turn!""" % imgloc return message
def prospectduranium(result): imgloc = static('wawmembers/duranium.gif') if result == 'TooMany': message = "Your fleet engineers have searched all they can today for duranium." elif result == 'Failure': message = "Unfortunately your expedition failed to find any duranium-rich asteroids." elif result == 'Success': message = """<img src="%s" alt="production"><br>Your expedition found a suitable duranium-rich asteroid! \ <br> You gain 3 duranium per turn.""" % imgloc return message
def prospectadamantium(result): imgloc = static('wawmembers/adamantium.gif') if result == 'TooMany': message = "Your fleet engineers have searched all they can today for adamantium." elif result == 'Failure': message = "Unfortunately your expedition failed to find any adamantium-rich asteroids." elif result == 'Success': message = """<img src="%s" alt="production"><br>Your expedition found a suitable adamantium-rich asteroid! \ <br> You gain 1 adamantium per turn.""" % imgloc return message
def salvagemission(result): from wawmembers.newsgenerator import salvagetext imgloc = static('wawmembers/salvage.gif') if result == 'NoSalvage': message = "There is no salvage for you to retrieve!" elif result == 'AlreadySalvaged': message = "You have already launched a salvage mission this turn!" else: message = """<img src="%s" alt="salvage"><br>Your salvage mission managed to return <br>\ %s in useful materials.""" % (imgloc, salvagetext(result[0],result[1],result[2])) return message
def shutdown(minetype): imgloc = static('wawmembers/closedmine.jpg') imgstr = '<img src="%s" alt="salvage"><br>' % imgloc result = minetype + (' refinery' if minetype == 'warpfuel' else ' mine') return "The workers are sad they have to find new jobs as your %s shuts down." % result
def reopen(minetype): adj = minetype + (' refinery' if minetype == 'warpfuel' else ' mine') imgstr = '<img src="%s" alt="salvage"><br>' % static('wawmembers/%s.gif' % minetype) return "%sThe workers are happy to be employed once more and are eager to resume working!" % imgstr ############ ### DOMESTIC ############
def arrest(result): imgloc = static('wawmembers/arrest.gif') if 95 < result <= 100: message = """<img src="%s" alt="arrest"><br>Some of the dissenters you arrested were collaborating<br> \ with the rebels! Rebel strength decreases.""" % imgloc elif 1 <= result <= 95: message = """<img src="%s" alt="arrest"><br>You imprison your opponents,<br>\ and the noise of dissent gets quieter.""" % imgloc elif result == 'ArrestedAll': message = "Your prisons are at full capacity!" return message
def citybuilding(result): imgloc = static('wawmembers/city.gif') if 95 < result <= 100: message = """<img src="%s" alt="city"><br> \ People flock to the new cities and their happiness<br> increases, as does their quality of life.""" % imgloc elif 1 <= result <= 95: message = """<img src="%s" alt="arrest"><br>People flock to the new cities and their happiness increases.""" % imgloc return message
def literacy(): imgloc = static('wawmembers/reading.gif') message = """<img src="%s" alt="literacy"><br> \ Your literacy program reaches many worldwide,<br>and people's quality of life increases as a result.""" % imgloc return message
def healthcare(): imgloc = static('wawmembers/healthcare.gif') message = """<img src="%s" alt="healthcare"><br> \ People's quality of life skyrockets as your healthcare<br>provisons reach millions around the globe.""" % imgloc return message ############## ### DIPLOMATIC ##############
def trainspy(result): imgloc = static('wawmembers/trainspy.gif') if result == 'TooMany': message = "You have sufficient spies already!" elif result == 'TooLong': message = "The name you have chosen is too long." elif result == 'Success': message = """<img src="%s" alt="trainspy"><br>Your intelligence agency immediately sets to work training a new spy.""" % imgloc return message
def research(outcome, result=None): imgloc = static('wawmembers/research.gif') if outcome == 'TooSoon': message = "You cannot order research again this turn - your scientists are still working!" elif outcome == 'TooMuch': message = "Your scientists cannot work through so much funding!" elif outcome == 'NoDur': message = "You do not have enough duranium to commence research!" elif outcome == 'NoTrit': message = "You do not have enough tritanium to commence research!" elif outcome == 'NoAdam': message = "You do not have enough adamantium to commence research!" elif outcome == 'Success': message = """<img src="%s" alt="research"><br>%s""" % (imgloc, result) return message
def shipyards(outcome): imgloc = static('wawmembers/research.gif') if outcome == 'Success': message = """<img src="%s" alt="shipyard"><br>Your engineers quickly construct an orbital shipyard and put it into service.""" % imgloc return message
def freighters(outcome, amount): imgloc = static('wawmembers/freighter.gif') from wawmembers.utilities import plural if outcome == 'Success': multiple = ('%s ' % amount if amount > 0 else '') message = """<img src="%s" alt="freighter"><br>Your fleet engineers get to work building your %s%s in the shipyards.""" \ % (imgloc, multiple, plural('freighter', amount)) return message
def training(outcome): imgloc = static('wawmembers/training.gif') if outcome == 'AtMax': message = "Your fleet is already at maximum training!" elif outcome == 'Success': message = """<img src="%s" alt="training"><br>Your fleet carries out its drills and there is<br> \ visible improvement in their tactics and cohesion!""" % imgloc return message