Static page with custom content depending on url - javascript

I used to use parts of the url address to add words to a page template when I worked with PHP.
I've started looking at static pages using https://gohugo.io and trying to get this function in JavaScript in order not to need to generate multiple pages (Although this is the point of static pages) since all url will use the same page template but with difrent text from the url.
Example (from my PHP site)
url = www.domain.tld/city/washington/
Where i get the word after /city/ and put the word "washington" in my page content.
url = www.domain.tld/city/somecityname/
Where i get the word after /somecityname/ and put the word "washington" in my page content.
I looked at https://gohugo.io/extras/datafiles/ and https://gohugo.io/extras/datadrivencontent/ but this wont fix it the way i want it to be. (although I have a csv file with the city names)
Page will be hosted on GitHub Pages so i can only use Javascript / jQuery for this function.

try this code for get city name
var qrStr1 = window.location.href;
var new1 = qrStr1.replace(':','');
var data1 = new1.split("/");
alert(data1[4]);// try with different index so you can find your value

Related

Iterare through background images

I'm trying to make a dynamically background that changes images every x seconds. But i want the images to be sourced from a directory in a django project. I have this piece of code but is hardcoded and limited.
var header = $('body');
var backgrounds = new Array(
'url(static/media/backgrounds/1.jpg)'
, 'url(static/media/backgrounds/2.jpg)'
, 'url(static/media/backgrounds/3.jpg)'
, 'url(static/media/backgrounds/4.jpg)'
, 'url(static/media/backgrounds/5.jpg)'
, 'url(static/media/backgrounds/6.jpg)'
, 'url(static/media/backgrounds/7.jpg)'
, 'url(static/media/backgrounds/8.jpg)'
, 'url(static/media/backgrounds/9.jpg)'
, 'url(static/media/backgrounds/10.jpg)'
);
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 5000);
header.css('background-image', backgrounds[0]);
Firstly you'll need to enumerate the images you want. For simple deployments, where static files will be on your filesystem (in STATIC_ROOT) and served from under /static/, something like
# Get absolute disk paths of files
backgrounds = glob.glob(os.path.join(settings.STATIC_ROOT, 'media', 'backgrounds', '*.jpg'))
# Turn into URLs
background_urls = [f'/static/media/backgrounds/{os.path.basename(bg)}' for bg in backgrounds]
will do; for a more robust solution, you'd probably want to use the staticfiles finders API to enumerate all files and turn them into URLs.
For serving that data to your view, a couple of options I can think of.
List the backgrounds in your view and pass the array into the template
Enumerate all of the background images' URLs into a list, pass it to the template
Render it into a JSON list: {{ background_urls|json_script:"backgrounds" }}
View returning Javascript fragment
Wire up a view that returns a JavaScript fragment with all the background URLs, e.g. var backgrounds = ["/static/foo.jpg"];
Use that in your view: <script src="{% url "background_list_js" %}"></script>
Your script would otherwise work as-is
View returning JSON payload
Wire up a view that returns a JSON object with all the background URLs, e.g. ["/static/foo.jpg"]
Use e.g. fetch() or another AJAX method to load the data before starting to change backgrounds
View returning a random background URL
Wire up a view that returns a JSON object with a single random background URL from the selection, e.g. {"url": "/static/foo.jpg"}
Use e.g. fetch() or another AJAX method to load the data every time you need a new background.
Custom template tag returning a Javascript fragment
Like option 1, but instead of having a separate view, register a simple template tag you can then use to inline the background array: <script>{% dump_backgrounds %}</script>

Visualforce link to create new Account/Contact/

I have a custom VisualForce page and would like via javascript to get the url to create a new account/contact.
I know I can do the following in the main apex code but I want to do something dynamically.
Create New Account
What is the easiest way to get the url to create a new object via javascript?
You can use this code in Javascript (if your script tag is inside a visualforce page):
var newAccountEndpoint = '{!URLFOR($Action.Account.New)}';
var newOpptyEndpoint = '{!URLFOR($Action.Opportunity.New)}';
Or as I stated before refer to pre made list of standard salesforce object prefixes

Scrapy: Modify rules for scraping web page

I've started to use scrapy for a project of mine to scrape data off a tennis website. Here is an example page that I want to scrape data off. As you can see, I want to scrape data for a tennis player. I need to recursively go through the entire page and gather 'Match Stats' (Theres a link titled 'Match Stats' next to every match) for a player's matches. I've already written code to parse data from the opened match stats popup. All I need to do now is open these match stats pages through the initial spider.
In all the examples I've read up on, we can write rules to navigate scrapy to the different urls that need scraping. In my case, I just want to write a rule to the different match stats links. However, if you saw the page I want to scrape, 'Match Stats' links are in the following format: javascript:makePopup('match_stats_popup.php?matchID=183704502'). As I've read online (I might be wrong!), scrapy can't deal with javascript and hence cant 'click' on that link. However, since the links are javascript popups, its possible to add the match_stats_popup.php?matchID=183704502 part of the link to the main url to get a standard html page:
http://www.tennisinsight.com/match_stats_popup.php?matchID=183704502
I am hoping I could modify the rules before scraping. In summary, I just want to find the links that are of the type: javascript:makePopup('match_stats_popup.php?matchID=183704502, and modify them so that they are now of the type http://www.tennisinsight.com/match_stats_popup.php?matchID=183704502
This is what I've written in the rules so far, which doesnt open any pages:
rules = (
Rule(SgmlLinkExtractor(allow='/match_stats_popup.php?matchID=\d+'),
'parse_match', follow=True,
),
)
parse_match is the method which parses data from the opened match stats popup.
Hope my problem is clear enough!
Using BaseSgmlLinkExtractor or SgmlLinkExtractor you can specify both the tag(s) from which to extract and process_value function used for extracting the link. There is nice example in the official documentation. Here is the code for your example:
class GetStatsSpider(CrawlSpider):
name = 'GetStats'
allowed_domains = ['tennisinsight.com']
start_urls = ['http://www.tennisinsight.com/player_activity.php?player_id=1']
def getPopLink(value):
m = re.search("javascript:makePopup\('(.+?)'\)", value)
if m:
return m.group(1)
rules = (
Rule(SgmlLinkExtractor(allow=r"match_stats_popup.php\?matchID=\d+",
restrict_xpaths='//td[#class="matchStyle"]',
tags='a', attrs='href', process_value=getPopLink), callback='parse_item', follow=True),
)
def parse_item(self, response):
sel = Selector(response)
i = TennisItem()
i['url_stats'] = response.url
return i

base link and search api

I am attempting to query a database through an API which I don't fully understand. I have been sent an example of the API being used with a keyword search form. The form is an html file and uses jquery return JSON documents, format items into an array array, and display.
I tried to build the design of my application and manipulate the form to work within my pages. The file the uses the API requires that the a base link be used.
<base href="{{app_root}}">
If I remove this base link my functionality of the search is lost. If I use the base link all of presentation and CSS is lost.
I thought maybe I could change the base link dynamically when I needed to call the search file with:
<script type="text/javascript">
function setbasehref(basehref) {
var thebase = document.getElementsByTagName("base");
thebase[0].href = basehref;
}
//setbasehref("{{app_root}}");
setbasehref("{{app_root}}");
</script>
Then use setbasehref() to change it back to my original base link, but that didn't work.
I'm new to javascript and JSON, and I'm not entirely sure what app_root is doing. Any thoughts?

How should I handle Asp.net MVC URLs in javascript calls?

I am attempting to write a javascript heavy portion of my Asp.net MVC Web App (this portion of the website is a RIA using Extjs). However, I have come up to a standstill at the correct way to handle URLs in the javascript.
For example, right now I have an Ajax call to the List action in the ObjectsController, which resides in the Reading area. The List action takes a parameter of documentId (int). As of right now, this maps to /Reading/Objects/List since I have no changed routing yet (the site is too young at the moment to finalize routes). Normally in a view, to put this URL in a string I would do #Html.Action("List", "Objects", new { area = "Reading", documentId = 3).
However, this doesn't work when dealing with javascript, since javascript isn't parsed by a viewengine.
To get around this, I have a very small view that returns javascript constants, such as URLs, that is loaded prior to my main application's js files. The issue is that I can't call Html.Action for this action because at constant creation time I (obviously) do not know what documentId the ajax calls are going to be, and if you exclude documentId from the Html.Action call an exception occurs. The documentId could change during the normal workflow of the application.
How do I handle this? I don't want to hardcode the URL to /Reading/Objects/List because if I change my routing for this (for a more user friendly json API), or this web app isn't hosted on the root of the domain, the URL will no longer be valid.
How does everyone else handle MVC URLs in their javascript calls?
Here's a safe technique that I've been using. Even if your route changes, your JavaScript will automatically conform to the new route:
<script>
var url = '#Url.Action("List", "Objects", new { area = "Reading", documentId = "_documentId_")';
var id = 100;
var finalUrl = url.replace('_documentId_', id);
</script>
"_documentId_" is essentially a dummy placeholder. Then inside my JavaScript, I replace "_documentId_" with the proper id value once I know what it is. This way, regardless of how your route is configured, your URL will conform.
Update: Dec 20
I just saw this interesting blog post. The author built a library that allows you to build routes inside of your JavaScript file with intellisense support in VisualStudio.
http://weblogs.asp.net/zowens/archive/2010/12/20/asp-net-mvc-javascript-routing.aspx
Personally I use unobtrusive javascript and avoid mixing markup with javascript. AJAX calls are normally triggered by clicking on some buttons or links:
#Html.ActionLink("click me", "List", "Objects",
new { area = "Reading", documentId = 3 }, new { id = "foo" })
and then in a separate js file I would attach and handle the onclick event (example with jquery):
$(function() {
$('#foo').click(function() {
$('#resultDiv').load(this.href);
return false;
});
});
As you can I didn't need to use any hardcoded URL in my javascript file. URLs should always be handled by the routing engine and generated with html helpers.
If it was a <form> instead of a link I would simply handle the onsubmit event (the same way) and use the form's action attribute to get the URL.
UPDATE:
After pointing out in the comments section that the documentId is known only at client-side you could do this:
#Html.ActionLink("click me", "List", "Objects",
new { area = "Reading" }, new { id = "foo" })
And then:
$(function() {
$('#foo').click(function() {
$('#resultDiv').load(this.href, { documentId: '123' });
return false;
});
});
Turns out, this was all solved by using Url.Action() instead of Html.Action(). Url.Action() is (so far) allowing me to generate URLS without all of the parameters. I am assuming that this only works when the route does not specify the parameters in the target URL itself.

Categories

Resources