有没有一种简单的方法来添加/删除/修改Tritium中URL的查询参数?

时间:2013-08-01 19:00:37

标签: moovweb tritium

我在另一篇文章中看到了一种非常谨慎的方法:How do I add a query parameter to a URL?

这似乎不太直观,但有人提到了使用即将推出的“URL范围”实现此目的的更简单方法。这个功能还没有出来,我将如何使用它?

2 个答案:

答案 0 :(得分:2)

如果您正在使用stdlib混音器,则应该能够使用URL范围,该范围提供辅助功能,以添加,查看,编辑和删除URL参数。这是一个简单的例子:

$original_url = "http://cuteoverload.com/2013/08/01/buttless-monkey-jams?hi=there"
$new_url = url($original_url) {
  log(param("hi"))
  param("hello", "world")
  remove_param("hi")
}
log($new_url)

Tritium Tester示例:http://tester.tritium.io/9fcda48fa81b6e0b8700ccdda9f85612a5d7442f

几乎忘了,链接到文档:http://tritium.io/current(您需要点击网址类别)。

答案 1 :(得分:0)

AFAIK,没有内置的方法。 我将在这里发布我如何附加查询参数,确保它已经在url上不会重复:

在你的functions / main.ts文件中,你可以声明:

# Adds a query parameter to the URL string in scope.
# The parameter is added as the last parameter in
# the query string.
#
# Sample use:
# $("//a[@id='my_link]") {
#   attribute("href") {
#     value() {
#       appendQueryParameter('MVWomen', '1')
#     }
#   }
# }
#
# That will add MVwomen=1 to the end of the query string,
# but before any hash arguments.
# It also takes care of deciding if a ? or a #
# should be used.
@func Text.appendQueryParameter(Text %param_name, Text %param_value) {
    # this beautiful regex is divided in three parts:
    #   1. Get anything until a ? or # is found (or we reach the end)
    #   2. Get anything until a # is found (or we reach the end - can be empty)
    #   3. Get the remainder (can be empty)
    replace(/^([^#\?]*)(\?[^#]*)?(#.*)?$/) {
        var('query_symbol', '?')
        match(%2, /^\?/) {
            $query_symbol = '&'
        }

        # first, it checks if the %param_name with this %param_value already exists
        # if so, we don't do anything
        match_not(%2, concat(%param_name, '=', %param_value)) {

            # We concatenate the URL until ? or # (%1),
            # then the query string (%2), which can be empty or not,
            # then the query symbol (either ? or &),
            # then the name of the parameter we are appending,
            # then an equals sign,
            # then the value of the parameter we are appending
            # and finally the hash fragment, which can be empty or not
            set(concat(%1, %2, $query_symbol, %param_name, '=', %param_value, %3))
        }       
    }
}

你想要的其他功能(删除,修改)可以类似地实现(通过在functions / main.ts中创建一个函数并利用一些正则表达式魔法)。

希望它有所帮助。